Reverse Vowels of a String Solutions in C++
Number 345
Difficulty Easy
Acceptance 44.2%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/reverse-vowels-of-a-string/// Author : Calinescu Valentin, Hao Chen// Date : 2016-04-30//Author: Calinescu Valentinclass Solution {public:string reverseVowels(string s) {list <char> vowels;set <char> vows;vows.insert('a');vows.insert('A');vows.insert('e');vows.insert('E');vows.insert('i');vows.insert('I');vows.insert('o');vows.insert('O');vows.insert('u');vows.insert('U');string result;for(int i = 0; i < s.size(); i++){if(vows.find(s[i]) != vows.end())vowels.push_back(s[i]);}for(int i = 0; i < s.size(); i++){if(vows.find(s[i]) != vows.end()){result.push_back(vowels.back());vowels.pop_back();}elseresult.push_back(s[i]);}return result;}};// Author: Hao Chen// 1) preset a dictionary table to look up vowels// 2) we have two pointer, the `left` one search vowels from the beginning to then end, the `right` one search from the end to the beginning.// 3) swap the left one and the right one until left >= right.class Solution {private:bool vowelsTable[256];public:Solution(){memset(vowelsTable, 0, sizeof(vowelsTable));vowelsTable['a']=true;vowelsTable['e']=true;vowelsTable['i']=true;vowelsTable['o']=true;vowelsTable['u']=true;vowelsTable['A']=true;vowelsTable['E']=true;vowelsTable['I']=true;vowelsTable['O']=true;vowelsTable['U']=true;}bool isVowels(char ch) {return vowelsTable[ch];}string reverseVowels(string s) {int left=0, right=s.size()-1;while ( left < right ) {while( !isVowels( s[left]) ) left++;while( !isVowels( s[right] ) ) right--;if (left >= right) break;swap(s[left], s[right]);left++; right--;}return s;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-vowels-of-a-string//// Author : liuyubobobo/// Time : 2016-12-06#include <iostream>#include <vector>#include <string>#include <cassert>#include <stdexcept>using namespace std;/// Two Pointers/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:string reverseVowels(string s) {int i = nextVowelIndex(s, 0);int j = preVowelIndex(s, s.size() - 1);while(i < j){swap(s[i], s[j]);i = nextVowelIndex(s, i + 1);j = preVowelIndex(s, j - 1);}return s;}private:int nextVowelIndex(const string &s, int index){for(int i = index ; i < s.size() ; i ++)if(isVowel(s[i]))return i;return s.size();}int preVowelIndex(const string &s, int index ){for(int i = index ; i >= 0 ; i --)if(isVowel(s[i]))return i;return -1;}bool isVowel(char c){char lowerc = tolower(c);return lowerc == 'a' || lowerc == 'e' || lowerc == 'i' || lowerc == 'o' || lowerc == 'u';}};int main() {cout << Solution().reverseVowels("hello") << endl;cout << Solution().reverseVowels("leetcode") << endl;return 0;}