Can someone please give me a suggestion on improvement?


  • 0
    V

    My 2-pointer solution is accepted, but it takes 200+ ms and I think there should be some room for improvement. Can someone give an idea? Thanks!

    class Solution(object):
        def reverseVowels(self, s):
            L = len(s)
            i = 0
            j = L - 1
            vowls = ['a','e','i','o','u','A','E','I','O','U']
            s = list(s)
            while i < j:
                while i < j and s[i] not in vowls:
                    i += 1
                while j > i and s[j] not in vowls:
                    j += -1
                if s[i] in vowls and s[j] in vowls:
                    temp = s[j]
                    s[j] = s[i]
                    s[i] = temp
                    i += 1
                    j += -1
                else:
                    break
            return ''.join(s)

  • 0
    J

    You can make the last conditional a bit easier...

    instead of checking

    s[i] in vowls and s[j] in vowls

    you can just check for

    i < j

    (given the logic, you already checked for "vowels" in the previous statements; if you didn't find vowels, i and j crossed paths).

    The rest looks perfectly right to me. Some extra "breaks" could be used not to double-check for the same i < j tests, but that obscures the code, makes it longer (i.e.: processor caches working worse), and don't think would produce a significant gain. An optimizing compiler would most probably take care of these.

    Just looks like this implementation of Python is just a bit slow ;-)


Log in to reply
 

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