Leetcode 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:Input: “hello”
Output: “holle”
Example 2:Input: “leetcode”
Output: “leotcede”
Note:
The vowels does not include the letter “y”.
题目大意:将一个字符串内的元音字母进行反转。
注意:原因字母不包括y,且包括大小写。
解题思路:采用头尾双指针,如果两个指针值都为元音字母则进行交换,否则往中间移动。时间复杂度为O(n).
代码1:
class Solution {
public:
bool isVowels(char c){
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
string reverseVowels(string s) {
int i = 0, j = s.size() - 1;
while(i < j)
{
if(isVowels(s[i]) && isVowels(s[j]))
swap(s[i++], s[j--]);
else if(isVowels(s[i]))
j--;
else
i++;
}
return s;
}
};
代码2:
class Solution {
public:
string reverseVowels(string s) {
int i = 0, j = s.size() - 1;
while(i < j)
{
i = s.find_first_of("aeiouAEIOU", i);
j = s.find_last_of("aeiouAEIOU", j);
if(i < j)
swap(s[i++], s[j--]);
}
return s;
}
};
577

被折叠的 条评论
为什么被折叠?



