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

题目

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

Example 1:
Given s =, return .

译文

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

举例:

Input Output
“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.

你可能感兴趣的:(每天十道编程题,string,leetcode,对撞指针,string函数)