翻转字符串中的元音字母 - easy

该博客主要讨论LeetCode的345题,即翻转字符串中的元音字母。通过思路分析、代码实现和算法优化,详细讲解了解决此问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

345. Reverse Vowels of a String

来源: LeetCode 345. Reverse Vowels of a String

题目描述

345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"
Example 2:

Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
vowel 元音

思路分析

pair 记录位置取出所有元音,翻转他们

代码

class Solution {
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
typedef pair<char, int> PI;
using VP = vector<PI>; 
public:
    string reverseVowels(string s) {
        VP arry;
        char a[] = {'a','e','i','o','u','A','E','I','O','U'};
        unordered_set<int> st(a, a+10); // 初始化集合
        REP(i,SIZE(s)){
            if(st.find(s[i]) != st.end()){
                arry.PB(MP(s[i],i));
            }
        }
        int i = 0, j = arry.size() - 1;
        while(i<j){
            char c = arry[i].first;
            arry[i].first = arry[j].first;
            arry[j].first = c;
            ++i;
            --j;
        } // 旋转
        for(auto a:arry){
            s[a.second] = a.first;
        }
        return s;
    }
};

算法分析

- 时间复杂度:O(n)
- 空间复杂度:O(1)

代码改进

双指针跟踪
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值