您的位置:首页 > 编程语言 > C语言/C++

LeetCode 345: Reverse Vowels of a String

2016-05-25 16:04 411 查看

345. Reverse Vowels of a String

Difficulty: Easy

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”.

思路

类似快速排序的一趟。

从字符串的两端交替地向中间扫描,扫描到的元音按顺序一一对应交换位置。

需要注意的是,不要漏了元音的大写。

代码

[C++]

class Solution {
public:
string reverseVowels(string s) {
if(s.length() <= 0)
return s;
int i = 0;
int j = s.length() - 1;
while(i < j) {
while(i < j && !IsVowels(s[i]))
i++;
while(i < j && !IsVowels(s[j]))
j--;
if(i < j) {
int temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;j--;
}
}
return s;
}
bool IsVowels(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;
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++