题目链接:https://leetcode.com/problems/reverse-vowels-of-a-string/
345. 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 "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
题目很简单,找到字符串中的元音字母,然后一一交换即可。
string reverseVowels(string s) {
int i=0,j=s.length()-1;
if(i>j)return s;
while(i<j){
while((s[j]!='a'&&s[j]!='e'&&s[j]!='i'&&s[j]!='o'&&s[j]!='u'&&s[j]!='A'&&s[j]!='E'&&s[j]!='I'&&s[j]!='O'&&s[j]!='U')&&i<j){
j--;
}
while((s[i]!='a'&&s[i]!='e'&&s[i]!='i'&&s[i]!='o'&&s[i]!='u'&&s[i]!='A'&&s[i]!='E'&&s[i]!='I'&&s[i]!='O'&&s[i]!='U')&&i<j){
i++;
}
if(i!=j){
char c=s[i];
s[i]=s[j];
s[j]=c;
i++;
j--;
}
}
return s;
}
每天一道题,保持新鲜感,就这样~