345.Reverse Vowels of a String

Tags: [two_pointers], [string], [vowel]

Com: {g}

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

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".


Better Solution:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s or len(s) <= 1:
            return s

        size = len(s)

        vowels = set(['a', 'e', 'i', 'o', 'u'])
        chars = list(s)
        left = 0
        right = size - 1
        while left < right:
            while left < right and chars[left].lower() not in vowels:
                left += 1
            while left < right and chars[right].lower() not in vowels:
                right -= 1

            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1

        return ''.join(chars)

Solution: two pointers

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return s

        vowels = {'a', 'e', 'i', 'o', 'u'}

        char_arr = list(s)
        left = 0
        right = len(char_arr) - 1

        while left < right:
            left_c = char_arr[left]
            right_c = char_arr[right]

            if left_c.lower() in vowels and right_c.lower() in vowels:
                char_arr[left], char_arr[right] = char_arr[right], char_arr[left]
                left += 1
                right -= 1
                continue

            if left_c.lower() not in vowels:
                left += 1

            if right_c.lower() not in vowels:
                right -= 1

        return ''.join(char_arr)

Note:

  • Time complexity = O(n), n is the length of the given string.

results matching ""

    No results matching ""