Reverse Vowels of a String 反转字符串中的元音字母

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:
给定 s = "hello", 返回 "holle".

示例 2:
给定 s = "leetcode", 返回 "leotcede".

注意:
元音字母不包括 "y".

思路:采用双指针法,左指针left指向0,右指针right指向s.size()-1,如果left

参考代码:

class Solution {
public:
bool checkVowel(char s1) {
	return s1 == 'a' || s1 == 'e' || s1 == 'i' || s1 == 'o' || s1 == 'u' || s1 == 'A' || s1 == 'E' || s1 == 'I' || s1 == 'O' || s1 == 'U';
}
string reverseVowels(string s) {
	if (s.empty()) return s;
	string res = s;
	int left = 0;
	int right = s.size() - 1;
	while (left < right) {
		while (left < right && !checkVowel(res[left])) left++;
		while (left < right && !checkVowel(res[right])) right--;
		if (left < right) {
			swap(res[left], res[right]);
			left++;
			right--;
		}
	}
	return res;
}
};





你可能感兴趣的:(算法,leetcode)