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

译文

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

举例:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值