LeetCode*345. Reverse Vowels of a string

1055 ワード

LeetCodeタイトルリンク
タイトル:
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1: Given s = "hello", return "holle".
Example 2: Given s = "leetcode", return "leotcede".
Note: The vowels does not include the letter "y".
答え:
class Solution {
public:
    string reverseVowels(string s) {
        string sv = "aeiouAEIOU";
        int i = 0;
        int j = s.length() - 1;
        
        while (i < j) {
            /* std::string::npos Means => static const size_t npos = -1; */
            while ((sv.find(s[i]) == std::string::npos) && (i < j)) {
                i++;
            }
            while ((sv.find(s[j]) == std::string::npos) && (i < j)) {
                j--;
            }
            
            if ((s[i] != s[j]) && (i < j)) {
                swap(s[i], s[j]);
            }
            
            i++;
            j--;
        }
        return s;
    }
};