Skip to content

Latest commit

 

History

History
50 lines (36 loc) · 1.04 KB

345.md

File metadata and controls

50 lines (36 loc) · 1.04 KB

Reverse Vowels of a String

Description

link


Solution

  1. Set two pointers to find all vowels and reverse them
  2. Find all vowels and use regex to replace it (re.sub)

Code

O(n)

class Solution:
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vocab = set(['a','e','i','o','u','A','E','I','O','U'])
        
        s = list(s)
        n = len(s)
        
        head = 0
        tail = n - 1
        
        while head < tail:
            while head < tail and s[head] not in vocab:
                head += 1
            while tail > head and s[tail] not in vocab:
                tail -= 1
            if head < tail:
                s[head], s[tail] = s[tail], s[head]
            head += 1
            tail -= 1
        
        return "".join(s)

    def reverseVowels2(self, s):
        vowels = re.findall('(?i)[aeiou]', s)
        return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)