[Leet Code] Reverse Vowels of a String
1 min readSep 20, 2021
Leet code: https://leetcode.com/problems/reverse-vowels-of-a-string/
Problem:
Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both cases.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Solution:
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
if s == "":
return ""
s = list(s)
ending = len(s) -1
starting = 0
while starting < ending:
if s[starting] in vowels:
if s[ending] in vowels:
temp = s[starting]
s[starting] = s[ending]
s[ending] = temp
starting += 1
ending -= 1
else:
ending -= 1
elif s[ending] in vowels and s[starting] not in vowels:
starting +=1
else:
starting += 1
ending -= 1
return "".join(s)