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”.
vowel : 元音 0,0
思路:扫描string,然后将其中的元音字母存放到一个容器中,然后倒序排列,最后输出
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool isVowel(char c) //判断是不是元音字母
{
switch(c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}
int main()
{
string s;
cin>>s;
vector<char> v;//存放输入字符串中的元音字母
for(int i=0; i<s.size(); i++)
{
if(isVowel(s[i]))
{
v.push_back(s[i]);
}
}
reverse(v.rbegin(),v.rend());//倒序排列
//输出!
int j=0;
for(int i=0; i<s.size(); i++)
{
if(isVowel(s[i]))
{
cout<<v[j++]<<"";
}
else
{
cout<<s[i]<<"";
}
}
}
- 思路2
只做一次循环
刚开始用迭代器来代替i , j 发现不行
有没有一种好的方法可以判断俩个迭代器始终保持一前一后呢?
#include <stack>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool isVowel(char c)
{
switch(c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}
void swapVowel(string s)
{
int i=0;
int j=s.size();
while(i < j)
{
while(!isVowel(s[i]))
++i;
while(!isVowel(s[j]))
--j;
if(i < j)
{
swap(s[i],s[j]);
i++;
j--;
}
}
cout<<s<<endl;
}
int main()
{
string s;
s="hello";
swapVowel(s);
}