345. Reverse Vowels of a String

题目:

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a''e''i''o', and 'u', and they can appear in both cases.

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

思路:

要交换位置,明显的双指针。先用哈希set记录下元音,可以只记录全大写或者全小写,在判断的时候多写一些语句也行,不过这里偷懒就把大小写元音都记录下来了。两个指针分别index = 0 和 n - 1,只要左指针的当前字母不在哈希set内,右移;同理右指针的当前字母不在哈希set内就左移,如果当前左指针index小于右指针index,则交换元素并且再次移动指针。最后返回字符串即可。

代码:

class Solution {
public:
    string reverseVowels(string s) {
        unordered_set<char> mp= {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
        int n = s.size(), i = 0, j = n - 1;
        while (i < j) {
            while (i < n && !mp.count(s[i]))
                i++;
            while ( j > 0 && !mp.count(s[j]))
                j--;
            if (i < j) {
                swap(s[i], s[j]);
                i++;
                j--;
            }
        }
        return s;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值