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”.
题目含义:只对string中的元音字符进行交换,英语中原因包括a、e、i、o、u。 题目分析:使用二分法的方法,使用两个指针分别从两端进行查找,直到均查找到符合条件的字符后进行交换。在题目中,不要忘记对元音的判断要包含大写和小写两种情况。
2. 题目解答–cpp
class Solution {
public:
// 判定传入的字符是否为元音
bool isVowels(
char t) {
char temp[] =
"aeiouAEIOU";
for (
int i =
0; i <
10; i++) {
if(t == temp[i]) {
return true;
}
}
return false;
}
string reverseVowels(
string s) {
char t;
int front =
0;
int end = s.size()-
1;
while (front < end) {
if (isVowels(s[front]) && isVowels(s[end])) {
t = s[front];
s[front] = s[end];
s[end] = t;
front++;
end--;
}
else {
if (!isVowels(s[front])) {
front++;
}
if (!isVowels(s[end])) {
end--;
}
}
}
return s;
}
};