Share My 92.84% Python Solution with Two Pointer, O(n)


  • 0
    M
    class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = {'a', 'e', 'i', 'o', 'u'}
        s = list(s)
        begin = 0
        end = len(s) - 1
    
        while begin < end:
            while begin < end and s[begin].lower() not in vowels:
                begin += 1
            while begin < end and s[end].lower() not in vowels:
                end -= 1
            s[begin], s[end] = s[end], s[begin]
            begin += 1
            end -= 1
    
        return ''.join(s)

  • 0
    A

    I use reduce function and i think it maybe faster, but i get TLE ...... T_T

    from functools import reduce
    return reduce(lambda x, y: x + y, s, '')

  • 0
    M

    Hi Aner,
    Thank you for your sharing!
    I use the python built-in module "timeit" to run benchmark for both reduce and join methods:

    We concatenate the items in the list: ['1', '2', '3', .. , '100'] for 100000 times, and it looks like that "join" is almost two times faster than reduce.

    timeit.timeit("''.join(str(n) for n in range(100))", number=100000)

    result: 2.9723191261291504

    timeit.timeit("reduce(lambda x, y: x+y, [str(n) for n in range(100)])", number = 100000)

    result: 4.32894492149353


Log in to reply
 

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