Judie 发表于 2023-6-2 11:13:26

【朱迪的LeetCode刷题笔记】345. Reverse Vowels of a String #Easy #Python #C++

本帖最后由 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()
      for index, item in enumerate(lst):
            slst] = lst[-(index+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 < back) {
                front++;
            }
            while (!isVowel(s) && front < back) {
                back--;
            }
            str = s;
            str = s;
            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) == 'a'tolower(s) == 'e'tolower(s) == 'i'tolower(s) == 'o'tolower(s) == 'u'){
                vowel_index.push_back(i);
                vowel_array.push(s);
            }
      }
      for(int i = 0; i < vowel_index.size(); i++) {
            s] = vowel_array.top();
            vowel_array.pop();
      }
      return s;
    }
};
页: [1]
查看完整版本: 【朱迪的LeetCode刷题笔记】345. Reverse Vowels of a String #Easy #Python #C++