一、題目
編寫一個函數,以字符串作爲輸入,反轉該字符串中的元音字母。
示例 1:
輸入: "hello" 輸出: "holle"
示例 2:
輸入: "leetcode" 輸出: "leotcede"
說明:
元音字母不包含字母"y"。
二、題解思路
- 題解思路:雙指針,即同時開始(正方向、反方向),正方向遍歷,反方向遍歷,碰到元音則交換位置,否則繼續往下查找。
三、代碼實現
-
C++代碼實現
class Solution {
public:
string reverseVowels(string s)
{
vector<char> nums = {'a','e','i','o','u','A','E','I','O','U'};
int i = 0,j = s.size()-1;
while(i<j)
{
while(!(find(nums.begin(),nums.end(),s[i])!=nums.end()) && i<j) //正方向不是元音,繼續查找
i++;
while(!(find(nums.begin(),nums.end(),s[j])!=nums.end()) && i<j) //反方向不是元音,繼續查找
j--;
char temp = s[i];
s[i++] = s[j];
s[j--] = temp;
}
return s;
}
};