一:题目
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".
二:解题思路
元音字母 a e i o u A E I O U
该题目的意思是反转一个字符串中的元音字母。第一个和最后一个元音字母交换,第二个和倒数第二个交换……
如果出现不成对匹配的情况,则不交换
三:代码实现
class Solution {
public:
bool isVowels(char c){
if(c=='a' || c=='e'|| c=='i'|| c=='o' || c=='u' || c=='A' || c=='E'|| c=='I'|| c=='O' || c=='U' )
return true;
return false;
}
string reverseVowels(string s) {
//反转字符串中的元音字母 a e i o u A E I O U
//该题目的意思是反转一个字符串中的元音字母。第一个和最后一个元音字母交换,第二个和倒数第二个交换……
//如果出现不成对匹配的情况,则不交换
int i=0;
int j=s.length()-1;
while(i<j){
while(!isVowels(s[i]) && i<j)
i++;
while(!isVowels(s[j]) && i<j)
j--;
swap(s[i],s[j]);
i++;
j--;
}
return s;
}
};