345. Reverse Vowels of a String

345. Reverse Vowels of a String

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”.

Analysis:
最简单直接的方法
Source Code(C++):

#include <iostream>
#include <string>
#include <stack>
#include <vector>
using namespace std;

class Solution {
public:
    string reverseVowels(string s) {
        vector<int> v;
        stack<int> vowels;
        for (int i=0; i<s.size(); i++){
            if (s.at(i)=='a' || s.at(i)=='e' || s.at(i)=='i' || s.at(i)=='o' || s.at(i)=='u' || s.at(i)=='A' || s.at(i)=='E' || s.at(i)=='I' || s.at(i)=='O' || s.at(i)=='U'){
                v.push_back(i);
                vowels.push(s.at(i));
            }
        }
        for (int i=0; i<v.size(); i++)
        {
            s.at(v.at(i)) = vowels.top();
            vowels.pop();
        }
        return s;
    }
};

int main() {
    Solution sol;
    cout << sol.reverseVowels("hello");
    return 0;
}

你可能感兴趣的:(345. Reverse Vowels of a String)