Leetcode | Reverse Vowels of a String (反转字符串中的元音字符)

Description:

Write a function that takes a string as input and reverse only the vowels of a string.
Attention:Vowels include captial letters

Example:

Input: “hello”
Output: “holle”

Input: “leetcode”
Output: “leotcede”

Ideas:

This's a typical problem solved with pointers.

My code:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        s_list = list(s)
        i = 0
        j = len(s_list) - 1
        while (i < j):
            x = s_list[i]
            y = s_list[j]
            if (x in vowels) and (y in vowels):
                temp = s_list[i]
                s_list[i] = y
                s_list[j] = temp
                i += 1
                j -= 1
            elif (x not in vowels):
                i += 1
            elif (y not in vowels):
                j -= 1
        return ''.join(s_list)

Execution time:80ms
Memory consumption:15.1MB

Discovery:

Dict traverse much faster then List traverse.

# use dict
def reverseVowels(s):
    """
    :type s: str
    :rtype: str
    """
    vowels = {
     'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    s_list = list(s)
    i = 0
    j = len(s_list) - 1
    while (i < j):
        x = s_list[i]
        y = s_list[j]
        if (x in vowels) and (y in vowels):
            s_list[i], s_list[j] = s_list[j], s_list[i] 
            i += 1
            j -= 1
        elif (x not in vowels):
            i += 1
        elif (y not in vowels):
            j -= 1
    return ''.join(s_list)

Execution time:36ms
Memory consumption:15.2MB

summary

In python, Dict can just have key and use it for searching while value is none.

你可能感兴趣的:(Leetcode,python,leetcode)