class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = 'aeiouAEIOU' vowel_list =  for chr in s: if chr in vowels: vowel_list.append(chr) ans = '' for chr in s: if chr in vowels: ans += vowel_list.pop() else: ans += chr return ans
this is my code.
as you can see, i have only 1 list and 1 more string for the final answer.
and all it does is O(2n) where n is the length of the string.
can anyone help me with this?
From what I understand, in some version of Python, using '+=' to concatenate two strings is inefficient. I think this occurs because strings in Python are immutable and therefore the concatenation is not completed in place.
Instead, you could try appending the characters to a list and turning the list into a string using
Also, a few other things that make your solution a little faster:
- Use a set instead of a string to store the different possible values of vowels
- Use a generator instead of a list to store all the vowels that occur in the string
Let me know if you would like me to elaborate on any of these items.