您的位置:首页 > 其它

【leetcode】 Reverse Vowels of a String(翻转字符串中出现的元音字母)

2017-04-21 12:41 381 查看

题目

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Given s =, return .

译文

编写一个将字符串作为输入并仅反转字符串元音的函数。

举例:

InputOutput
“leetcode”“leotcede”
“hello”“holle”
解法一:

string reverseVowels(string s) {
char dict[256] = {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 start = 0, end = (int)s.size() - 1;
while(start < end){
while(start < end && dict[s[start]] == 0) start++;
while(start < end && dict[s[end]] == 0) end--;
swap(s[start],s[end]);
start++;end--;
}
return s;
}


解法二:借助库函数

tring 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;
}


附录

(一)

size_t find_first_of ( const string& str, size_t pos = 0 ) const;

size_t find_first_of ( const char* s, size_t pos, size_t n ) const;

size_t find_first_of ( const char* s, size_t pos = 0 ) const;

size_t find_first_of ( char c, size_t pos = 0 ) const;

Find character in string

Searches the string for any of the characters that are part of either str, s or c, and returns the position of the first occurrence in the string.

When pos is specified the search only includes characters on or after position pos, ignoring any possible occurrences at previous character positions.

(二)

size_t find_last_of ( const string& str, size_t pos = npos ) const;

size_t find_last_of ( const char* s, size_t pos, size_t n ) const;

size_t find_last_of ( const char* s, size_t pos = npos ) const;

size_t find_last_of ( char c, size_t pos = npos ) const;

Find character in string from the end

Searches the string from the end for any of the characters that are part of either str, s or c, and returns the position of the last occurrence in the string.

When pos is specified the search only includes characters on or before position pos, ignoring any possible occurrences at character positions after it.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: