345. Reverse Vowels of a String

Numeric_combo·2024년 10월 30일

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

Example 1:

Input: s = "IceCreAm"

Output: "AceCreIm"

Explanation:

The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".

Example 2:

Input: s = "leetcode"

Output: "leotcede"

Constraints:

1 <= s.length <= 3 * 105
s consist of printable ASCII characters.

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
        s = list(s)  # Convert string to a list for easy manipulation
        left, right = 0, len(s) - 1

        while left < right:
            # Move left pointer to the right until it finds a vowel
            while left < right and s[left] not in vowels:
                left += 1
            # Move right pointer to the left until it finds a vowel
            while left < right and s[right] not in vowels:
                right -= 1
            # Swap the vowels
            if left < right:
                s[left], s[right] = s[right], s[left]
                left += 1
                right -= 1

        return ''.join(s)  # Convert list back to string

easy래매...로직이 하나 떠오르긴 했는데 이게 가능은하겠지만 굉장히 복잡해질 것 같아서 흠 뭐지 좀 고민하다가 결국 답을 봤는데 투포인터를 쓰는 거였다. 떠올리지 못해서 좀 아쉬웠지만 이런 경우엔 투포인터 쓴다는 걸 깨달았으니 만족. 참고로 len() 함수는 상기 겸 쓰는 건데 스트링의 경우 character의 갯수(=길이)를 세는 거지만 포인터를 사용할 때는 갯수가 아니라 index를 사용하기 때문에 주어진 스트링의 마지막 캐릭터를 지칭할 때는 len(s) -1 로 선언해야한다. 즉, 'hello'가 있을 때 len()은 5지만, 포인터의 입장에선 길이가 아니라 index를 지칭하는 것이고, 파이썬의 index는 0부터 시작하기 때문에 포인터가 스트링의 가장 왼쪽을 지칭할 때는 0부터 시작하고, 반대로 가장 오른쪽부터 지칭할 때는 len(s) - 1로 선언해야한다. 잊지 말자.

swap the vowels의 과정은 다음과 같다.

First Loop (left < right):

s[left] = 'h' (not a vowel), so move left rightward.

Update: left = 1 (points to 'e').

s[right] = 'o' (vowel), so right pointer doesn’t move.

Swap: Now sleft and sright are both vowels, so we swap them.

After swap: s = ['h', 'o', 'l', 'l', 'e']

Move both pointers inward:

left = 2 (points to 'l')
right = 3 (points to 'l')

Second Loop (left < right):

s[left] = 'l' (not a vowel), so move left rightward.
Update: left = 3
s[right] = 'l' (not a vowel), so move right leftward.
Update: right = 2

End Condition:

Now left >= right (left = 3, right = 2), so the loop ends.

profile
덕질기록용

0개의 댓글