leecode 解题总结:345. Reverse Vowels of a String

#include 
#include 
#include 
#include 
#include 
using namespace std;
/*
问题:
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".

分析:题目的意思只是将字符串中的元音字母进行逆置。
等同于从后向前和从前向后,找到两个元音字母进行交换即可,
元音字母:a e i o u
如果只有一个元音字母,就不交换

输入:
hello
leetcode
输出:
holle
leotcede

报错:
Input:
"aA"
Output:
"aA"
Expected:
"Aa"

关键:
1 果然元音字母包含大写字母,细心
*/

class Solution {
public:
    string reverseVowels(string s) {
        if(s.empty())
		{
			return "";
		}
		unordered_set vowels;
		string str = "aeiouAEIOU";
		int size = str.length();
		for(int i = 0 ; i < size ; i++)
		{
			vowels.insert(str.at(i));
		}
		int len = s.length();
		int low = 0;
		int high = len - 1;
		while(low < high)
		{
			//从前向后找到第一个元音字母
			while(low < high && vowels.find(s.at(low)) == vowels.end())
			{
				low++;
			}
			while(low < high && vowels.find(s.at(high)) == vowels.end())
			{
				high--;
			}
			//交换这两个元素
			swap(s.at(low) , s.at(high));
			low++;
			high--;//交换后指针移动
		}
		return s;
    }
};
void process()
{
	 string value;
	 Solution solution;
	 while(cin >> value )
	 {
		 string result = solution.reverseVowels(value);
		 cout << result << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


你可能感兴趣的:(leecode)