345. Reverse Vowels of a String

 

Promble

link: https://leetcode.com/problems/reverse-vowels-of-a-string/description/

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.

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

Approach 1

Thought

  1. def l:list to store the vowels, from front to back.
  2. def v:list is vowels, include lower and upper.
  3. loop i in s, if i in v, append i to l. (left to right)
  4. def ss:str to store the final result.
  5. loop j in s:
    1. if j in v: ss += l[-1], l.pop(-1) # from back to front, add into ss and pop.
    2. else: ss+=j # not change
  6. return ss

Code

class Solution:
    def reverseVowels(self, s: str) -> str:
        l = []
        v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        
        for i in s:
            if i in v:
                l.append(i)

        print(l)

        ss = ""
        for j in s:
            if j in v:
                ss += l[-1]
                l.pop(-1)
            else:
                ss+=j

        return ss

Approach 2

two pointer

Thought

  1. def vowels:list to store the vowels.
  2. def s:list is the list of string.
  3. def l, r:int is the 0 and len(s)-1
  4. while r>l:
    1. def lS:str is the left str in l.
    2. def rS:str is the right str in l.
    3. if lS not in vowels: l+1, continue # continue will skip the reset of the code.
    4. if rS not in vowels: r-1, continue # continue will skip the reset of the code.
    5. s[l], s[r] = s[r], s[l] # change the l and r, when s[l] and s[r] all in vowels.
    6. l, r = l+1, r-1 # move the l and r, when s[l] and s[r] all in vowels.
  5. return the s in str format.

Code

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ['a', 'e', 'i', 'o', 'u']
        s = list(s)
        l, r = 0, len(s)-1

        while r > l:
            lS = s[l].lower()
            rS = s[r].lower()

            if lS not in vowels:
                l += 1 
                continue 

            if rS not in vowels:
                r -= 1
                continue 
            
            s[l], s[r] = s[r], s[l]
            l, r = l+1, r-1

        return ''.join(s)