Leetcode

[Leetcode] 345. Reverse Vowels of a String

mjk- 2025. 4. 4. 16:19

문제

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 * 105s consist of printable ASCII characters.

 

풀이

이 문제는 two pointers를 사용하면 된다.

two pointers = 3 while loops 라고 외우자

 

코드

int isVowel(char c) {
    c = tolower(c);
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

char* reverseVowels(char* s) {
    int left = 0, right = strlen(s) - 1;
    
    while (left < right) {
        while (left < right && !isVowel(s[left])) {
            left++;
        }
        while (left < right && !isVowel(s[right])) {
            right--;
        }
        
        if (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
    
    return s;
}