Easy&clear C++ using hash table


  • 0
    F
    class Solution {
    public:
        string reverseVowels(string s) {
            string result="";
            if(s.length()==0) return result;
            unordered_map<char,int>vowels;
            vowels['a']++;vowels['e']++;vowels['i']++;vowels['o']++;vowels['u']++;
            vowels['A']++;vowels['E']++;vowels['I']++;vowels['O']++;vowels['U']++;
            string temp ="";
            for(int i=s.length()-1;i>=0;i--){
                if(vowels[s[i]]==1) temp+=s[i];
            } 
            int k=0;
            for(int i=0;i<s.length();i++) {
                if(vowels[s[i]]==1) { 
                    result+= temp[k]; k++;
                }
                else result+=s[i];
            }
            return result;
        }
    };

  • 0
    P
        class Solution {
    public:
        string reverseVowels(string s) {
            vector<char> vow; 
            for(int i = 0; i < s.length(); i++)
            {
                if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')
                {
                    vow.push_back(s[i]);
                }
            }
            int count = 0;
            for (int i = 0; i < s.length(); i++)
            {
                if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u'  || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')   
                {
                    s[i] = vow[vow.size() - count - 1];
                    count++;
                }
            }
            return s;
            
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.