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

来源:互联网 发布:微山湖武工队知乎 编辑:程序博客网 时间:2024/06/05 07:02
#include <iostream>#include <stdio.h>#include <vector>#include <string>#include <unordered_set>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如果只有一个元音字母,就不交换输入:helloleetcode输出:holleleotcede报错:Input:"aA"Output:"aA"Expected:"Aa"关键:1 果然元音字母包含大写字母,细心*/class Solution {public:    string reverseVowels(string s) {        if(s.empty()){return "";}unordered_set<char> 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;}

0 0