Give you a string s
, Invert only all vowels in the string , And return the result string .
Vowels include 'a'
、'e'
、'i'
、'o'
、'u'
, And may appear in both case .
example :
Input :s = "hello" Output :"holle"
analysis :
Only vowels in a string are conditionally constrained , So we just need to store the vowels , Then you can reverse replace the vowels of the string , The first thing that comes to mind when you meet the condition of "first in, last out" is the stack .
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
stack = [] # Create a stack
for i in s: # Storing vowels
if i in 'aeiouAEIOU':
stack.append(i)
res = '' # Result string
for j in s:
if j not in 'aeiouAEIOU': # Not a direct reproduction of vowels
res += j
else:
res += stack.pop() # If it is a vowel, it is reversed
return res