Skip to content

Latest commit

 

History

History
30 lines (28 loc) · 992 Bytes

345. Reverse Vowels of a String.md

File metadata and controls

30 lines (28 loc) · 992 Bytes

345. Reverse Vowels of a String (Easy)

[tag] two pointers

  • brute force:
    • use for loop to find all vowels and index.
    • reverse them and puth them back to place.
    • hello --> e (1) and o (4) a (5) -> a(1), o(4), e(5)
  • two pointers:
    • use l and r pointers move if not vowels
    • if both are vowels, swap them, and both move one more
    • if they meet exist so while condition will be while l < r
class Solution:
    def reverseVowels(self, s: str) -> str:
        if not s:
            return
        s_list = list(s)
        l, r = 0, len(s_list) - 1
        vowels = list('aeiouAEIOU')
        # vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        while l < r:
            while l < r and s_list[l] not in vowels:
                l += 1
            while l < r and s_list[r] not in vowels:
                r -= 1
            s_list[l], s_list[r] = s_list[r], s_list[l]
            l, r = l + 1, r - 1
        return ''.join(s_list)