leetcode345——Reverse Vowels of a String(C++),leetcode345vowels
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".
個人博客:http://www.cnblogs.com/wdfwolf3/。
這道題在逆置字符串的基礎上加入了限制,只做原音(aeiouAEIOU)的逆置,不理會非原因的字符。在這裡我主要針對如何判斷原因講述幾個方法,至於字符串逆置不再討論,可以看我專門寫Reverse String的博文http://www.cnblogs.com/wdfwolf3/p/5484675.html。
1.調用函數判斷(16ms)
這個最基本最容易想到實現,沒什麼難度。

![]()
class Solution {
public:
string reverseVowels(string s) {
int i=0,j=s.length()-1;
while(i<j)
{
while((isVowel(s[i])==false)&&(i<j))
{
i++;
}
while((isVowel(s[j])==false)&&(i<j))
{
j--;
}
swap(s[i],s[j]);
i++;
j--;
}
return s;
}
bool isVowel(char c)
{
if((c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u')||(c=='A')||(c=='E')||(c=='I')||(c=='O')||(c=='U'))
return true;
return false;
}
};
View Code
2.利用數組模擬哈希表的方式(12ms)

![]()
class Solution {
public:
string reverseVowels(string s) {
int dict[128] = {0};
dict['a']=1;
dict['A']=1;
dict['e']=1;
dict['E']=1;
dict['i']=1;
dict['I']=1
dict['o']=1;
dict['O']=1;
dict['u']=1;
dict['U']=1;
int i=0,j=s.length()-1;
while(i<j)
{
while((dict[s[i]]==0)&&(i<j))
{
i++;
}
while((dict[s[j]]==0)&&(i<j))
{
j--;
}
swap(s[i],s[j]);
i++;
j--;
}
return s;
}
};
View Code
3.利用字符串查找函數string.find()或者string.find_first_of()。關於這兩個函數在最後面詳細介紹。

![]()
class Solution {
public:
string reverseVowels(string s) {
string vowel="aeiouAEIOU";
int i=0,j=s.length()-1;
while(i<j)
{
while((vowel.find(s[i])==string::npos)&&(i<j))
{
i++;
}
while((vowel.find(s[j])==string::npos)&&(i<j))
{
j--;
}
swap(s[i],s[j]);
i++;
j--;
}
return s;
}
};
View Code(12ms)

![]()
string vowel="aeiouAEIOU";
int i=0,j=s.length()-1;
while(i<j)
{
i=s.find_first_of(vowel,i);
j=s.find_last_of(vowel,j);
if(i>=j)
break;
swap(s[i],s[j]);
i++;
j--;
}
return s;
View Code(13ms)
P.S.
1.str1.find(str2, , )
作用是在str1中查找str2的位置,str2可以是單個字符,字符串變量或者字符串;第二個參數是str1的起始查找位置,即從str1的哪個位置開始查找,默認為0;第三個參數是只查找str2的前多少個字符,默認是str2的全部。可以沒有後兩個參數。返回的是str2首個字符在str1的位置,如果沒有找到的話返回string::npos,它有幾層含義,本身它是一個常量-1,當作為返回值時表示查找失敗;在使用下標時,它大於任何下標(邏輯上概念),可以看作字符串的盡頭或者說結尾。
2.string.find_first_of(str, , )
參數作用同上。但是函數作用是不同的,返回的值是str中任何一個字符首次在string中出現的位置。上一個函數相當於匹配,這個更像篩選。
3.string.find_last_of(str, , )
參數作用同上,作用也同上。區別是這個是向前查找的,從第二個參數位置開始向前找到str中任何一個字符首次在string中出現的位置,自然默認參數為string::npos。