本题为谷歌面试题。
问题描述:
一、第一种方法:对撞指针法
#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;
}
方法二:使用find_first_of
class Solution {
public:
string reverseVowels(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
i = s.find_first_of("aeiouAEIOU", i);
j = s.find_last_of("aeiouAEIOU", j);
if (i < j) {
swap(s[i++], s[j--]);
}
}
return s;
}
}
关于find_first_of函数:
搜索字符串,以匹配其参数中指定的任何字符。当指定pos时,搜索只包括位置pos的字符,忽略pos之前的任何可能出现的情况。
语法:
size_t find_first_of (const string& str, size_t pos = 0) const;
参考资料: