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".
這道題讓我們翻轉字符串中的元音字母,元音字母有五個a,e,i,o,u,需要注意的是大寫的也算,所以總共有十個字母。我們寫一個isVowel的函數來判斷當前字符是否為元音字母,如果兩邊都是元音字母,那么我們交換,如果左邊的不是,向右移動一位,如果右邊的不是,則向左移動一位,參見代碼如下:
解法一:
class Solution { public: string reverseVowels(string s) { int left = 0, right= s.size() - 1; while (left < right) { if (isVowel(s[left]) && isVowel(s[right])) { swap(s[left++], s[right--]); } else if (isVowel(s[left])) { --right; } else { ++left; } } return s; } bool isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } };
或者我們也可以用自帶函數find_first_of和find_last_of來找出包含給定字符串中任意一個字符的下一個位置進行交換即可:
解法二:
class Solution { public: string reverseVowels(string s) { int left = 0, right = s.size() - 1; while (left < right) { left = s.find_first_of("aeiouAEIOU", left); right = s.find_last_of("aeiouAEIOU", right); if (left < right) { swap(s[left++], s[right--]); } } return s; } };
我們也可以把元音字母都存在一個字符串里,然后每遇到一個字符,就到元音字符串里去找,如果存在就說明當前字符是元音字符,參見代碼如下:
解法三:
class Solution { public: string reverseVowels(string s) { int left = 0, right = s.size() - 1; string t = "aeiouAEIOU"; while (left < right) { if (t.find(s[left]) == string::npos) ++left; else if (t.find(s[right]) == string::npos) --right; else swap(s[left++], s[right--]); } return s; } };
類似題目:
參考資料:
https://leetcode.com/discuss/99048/easy-to-understand-c-solution
https://leetcode.com/discuss/99047/super-clean-solution-using-find_first_of-and-find_last_of
https://leetcode.com/discuss/99062/java-two-pointers-solution-easy-understand-finish-interview