1.问题描述
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”.
来自 https://leetcode.com/problems/reverse-vowels-of-a-string/description/
2.题目分析:
对字符串中的元音经行反转,元音字母有aeiouAEIOU,我们要判断是否是元音,并且存在可交换的元音对。
//我的代码:(beats 39%)
bool isVowel(char c)
{
string v = "aeiouAEIOU";
for (int i = 0; i < v.length(); i++)
{
if (c == v[i])
return true;
}
return false;
}
string reverseVowels(string &s)
{
int i = 0;
int j = s.length() - 1;
while (i < j)
{
if (!isVowel(s[i]))
{
i++;
continue;
}
if (!isVowel(s[j]))
{
j--;
continue;
}
swap(s[i], s[j]);
i++;
j--;
}
return s;
}
//别人家的代码:
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;
}