코딩테스트/Python

[LeetCode] 345. Reverse Vowels of a String

swwho 2025. 3. 19. 17:23
728x90
반응형

🔗 Problem Link

https://leetcode.com/problems/reverse-vowels-of-a-string/description/


❔Thinking

  • 영단어가 주어지면, 모음(a,e,i,o,u)만을 역순으로 재배치하여 반환한다. (abe -> eba)
  • 알파벳은 소문자와 대문자를 구분한다.

💻Solution

1. 단어에 포함된 모음을 배열에 담고, 해당 배열에서 pop 하여 순서 재배치

def reverseVowels(self, s: str) -> str:
    vowels_set = set(['a','e','i','o','u','A','E','I','O','U'])
    vowels_list = []
    s = list(s)
    for char in s:
        if char in vowels_set:
            vowels_list.append(char)
    
    for i in range(len(s)):
        if s[i] in vowels_set:
            s[i] = vowels_list.pop()
    return ''.join(s)

 

2. 투 포인터를 활용하여 양쪽에서 모음을 찾고, 두 위치의 알파벳을 교환

def reverseVowels(self, s: str) -> str:
    s = list(s)
    left, right = 0, len(s)-1
    vowels = set('AEIOUaeiou')
    
    while left < right:
        while left < right and s[left] not in vowels:
            left += 1
        while left < right and s[right] not in vowels:
            right -= 1
        s[left], s[right] = s[right], s[left]
        left+=1
        right-=1
    
    return ''.join(s)

🗝️keypoint

  1. 모음의 대소문자를 구분한다.
  2. 양쪽에서 모음을 찾고 서로의 위치를 교환하면 한번에 해결할 수 있다.