LeetCode75——Day5

文章目录

一、题目

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 lower and upper cases, more than once.

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.

二、题解

双指针思路,定义左指针left和右指针right

cpp 复制代码
class Solution {
public:
    string reverseVowels(string s) {
        int n = s.length();
        unordered_map<char,int> map;
        map['A'] = 1;
        map['a'] = 1;
        map['E'] = 1;
        map['e'] = 1;
        map['I'] = 1;
        map['i'] = 1;
        map['O'] = 1;
        map['o'] = 1;
        map['U'] = 1;
        map['u'] = 1;
        int left = 0;
        int right = n - 1;
        while(left < right){
            while(left < n && !map.count(s[left])) left++;
            while(right > -1 && !map.count(s[right])) right--;
            if(left < right) swap(s[left++],s[right--]);
        }
        return s;
    }
};
相关推荐
地平线开发者4 小时前
J6B vio scenario sample
算法
BothSavage16 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn16 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽17 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
郝学胜_神的一滴17 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
见过夏天1 天前
C++ 基础入门完全指南
c++
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法