344. Reverse String

Problem:

Write a function that takes a string as input and returns the string reversed.

Example:

Given s = "hello", return "olleh".

Solution 1

Using list comprehension:

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]

Solution 2

Using two pointers:

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = list(s)
        i, j = 0, len(s) - 1
        while i <= j:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1
        return ''.join(s)

345. Reverse Vowels of a String

Problem:

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".

Solution 1

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = 'aeiouAEIOU'
        s = list(s)
        i, j = 0, len(s) - 1
        while i <= j:
            if s[i] in vowels and s[j] in vowels:
                s[i], s[j] = s[j], s[i]
            elif s[i] in vowels:
                i -= 1
            elif s[j] in vowels:
                j += 1
            i += 1
            j -= 1
        return ''.join(s)

Solution 2

Using stack.

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = 'aeiouAEIOU'
        s = list(s)
        index, word = [], []
        for i in range(len(s)):
            if s[i] in vowels:
                index.append(i)
                word.append(s[i])
        for i in index:
            s[i] = word.pop()
        return ''.join(s)