LeetCode - Reverse Vowels of a String

2236 ワード

Question
Link : https://leetcode.com/problems/reverse-vowels-of-a-string/
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1: Given s = “hello”, return “hole”.
Example 2: Given s = “leetcode”, return “leotcede”.
Code
この問題は前の反転文字列のアップグレード版であるLeetCode-Reverse Stringと見なすことができ、その中の3つ目の実現方法を利用して、母音文字が再び位置を交換するかどうかを判断することができます.(C++ : 12ms)
class Solution {
public:
    string reverseVowels(string s) {
        int start = 0, end = s.size() - 1;
        while(true){
            while(!isVowel(s[start]) && start < s.size())
                start++;
            while(!isVowel(s[end]) && end >= 0)
                end--;
            if(start < end)
                swap(s[start++], s[end--]);
            else
                break;
        }
        return s;
    }

    bool isVowel(char ch){
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'
            || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
    }
};