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".
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ arr = list(s) vows = {"a", "e", "i", "o", "u"} i, j = 0, len(arr)-1 while i<j: if arr[i].lower() in vows: if arr[j].lower() in vows: arr[i], arr[j] = arr[j], arr[i] i += 1 j -= 1 else: i += 1 return "".join(arr)
or
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ arr = list(s) vows = {"a", "e", "i", "o", "u"} i, j = 0, len(arr)-1 while i<j: if arr[i].lower() in vows: while i<j and arr[j].lower() not in vows: j -= 1 if i == j: break arr[i], arr[j] = arr[j], arr[i] j -= 1 i += 1 return "".join(arr)
or 都用贪心:
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ arr = list(s) vows = {"a", "e", "i", "o", "u"} i, j = 0, len(arr)-1 while i<j: while i<j and arr[i].lower() not in vows: i += 1 while i<j and arr[j].lower() not in vows: j -= 1 if i < j: arr[i], arr[j] = arr[j], arr[i] j -= 1 i += 1 return "".join(arr)
或者是two sum的思路,
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ arr = list(s) vows = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} i, j = 0, len(arr)-1 while i<j: l, r = arr[i] in vows, arr[j] in vows if l and r: arr[i], arr[j] = arr[j], arr[i] j -= 1 i += 1 elif l and not r: j -= 1 elif not l and r: i += 1 else: i += 1 j -= 1 return "".join(arr)
此外,还有使用stack存储vows的做法,两次遍历,第一次生成stack,第二次在遇到vows时候直接pop stack里的字符替换掉。
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ arr = list(s) vows = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} stack = [] for i,c in enumerate(arr): if c in vows: stack.append(c) for i,c in enumerate(arr): if c in vows: arr[i] = stack.pop() return "".join(arr)