鱼C论坛

 找回密码
 立即注册
查看: 894|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】345. Reverse Vowels of a String #Easy #Python #C++

[复制链接]
发表于 2023-6-2 11:13:26 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Judie 于 2023-6-1 22:22 编辑

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: "hole"

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

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

Judy
Python
class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        slst= list(s)
        vowels = 'aeiouAEIOU'
        lst = []
        for index, item in enumerate(s):
            if vowels.count(item) > 0:
                lst.append([index, item])
        for index, item in enumerate(lst):
            slst[item[0]] = lst[-(index+1)][1]
        return ''.join(slst)

Mike
C++ slightly faster
class Solution {
public:
    bool isVowel(char c) {
        return (c == 'a'  c == 'e'  c == 'i'  c == 'o'  c == 'u'  c == 'A'  c == 'E'  c == 'I'  c == 'O' || c == 'U');
    }
    string reverseVowels(string s) {
        string str = s;
        int front = 0;
        int back = s.length() - 1;
        while (back > front) {
            while (!isVowel(s[front]) && front < back) {
                front++;
            }
            while (!isVowel(s[back]) && front < back) {
                back--;
            }
            str[front] = s[back];
            str[back] = s[front];
            front++;
            back--;
        }
        return str;
    }
};

Gray
C++ stack version
class Solution {
public:
    string reverseVowels(string s) {
        vector<int> vowel_index;
        stack<char> vowel_array;
        for(int i = 0; i < s.size();i++){
            if(tolower(s[i]) == 'a'  tolower(s[i]) == 'e'  tolower(s[i]) == 'i'  tolower(s[i]) == 'o'  tolower(s[i]) == 'u'){
                vowel_index.push_back(i);
                vowel_array.push(s[i]);
            }
        }
        for(int i = 0; i < vowel_index.size(); i++) {
            s[vowel_index[i]] = vowel_array.top();
            vowel_array.pop();
        }
        return s;
    }
};

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-28 01:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表