[Leetcode]345. Reverse Vowels of a String

2024. 7. 26. 12:32Algorithm

1. Problem : 

https://leetcode.com/problems/reverse-vowels-of-a-string/description/?envType=study-plan-v2&envId=leetcode-75

 

2. Solution 1 : 

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowel_list = ["a","e","i","o","u","A","E","I","O","U"]
        string_list = list(s)
        
        left,right = 0,len(string_list)-1 
        while left < right:
            if string_list[left] in vowel_list and string_list[right] in vowel_list:
                string_list[left],string_list[right] = string_list[right], string_list[left] 
                left += 1 
                right -= 1 
            elif string_list[left] in vowel_list:
                right -= 1 
            elif string_list[right] in vowel_list:
                left += 1 
            else:
                left += 1 
                right -= 1
        return "".join(string_list)

위 solution은 str을 리스트로 만든 다음, left, right (two pointer)를 이용해, 모음이 나오는 순간, 서로 바꿔치기하는 코드다. 

그런 다음, return으로 str을 다시 return 한다. 

 

3. solution 2 : 

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set('aeiouAEIOU')
        s = list(s)
        i, j = 0, len(s) - 1
    
        while i < j:
            while i < j and s[i] not in vowels:
                i += 1
            while i < j and s[j] not in vowels:
                j -= 1
            if i < j:
                s[i], s[j] = s[j], s[i]
                i += 1
                j -= 1
                
        return ''.join(s)

이 solution 같은 경우 첫 번째 solution과 같은 solution이다. 하지만 표현 방식만 다르다. while문안에 while문을 이용해, logic을 작성했다.