Python solution with detailed explanation

  • 0


    Reverse Vowels of a String

    Two pointer solution

    • st and end and move st until you hit a vowel. Then move end until you hit a vowel. Then swap.
    • Terminating condition: st < end
    class Solution(object):
        def reverseVowels(self, s):
            :type s: str
            :rtype: str
            sa = [x for x in s]
            st, end = 0, len(sa) - 1
            vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
            while st < end:
                while st < end and sa[st] not in vowels:
                    st += 1
                while st < end and sa[end] not in vowels:
                    end -= 1
                if st != end:
                    sa[st], sa[end] = sa[end], sa[st]
                st, end = st+1, end-1
            return "".join(sa)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.