I was practicing programming by Python on leetcode.
So this is the problem: https://leetcode.com/problems/reverse-vowels-of-a-string/
And this is my answer:
def reverseVowels(s):
result = list(s)
v_str = 'aeiouAEIOU'
v_list = [item for item in s if item in v_str]
v_list.reverse()
v_index = 0
for i, item in enumerate(s):
if item in v_list:
result[i] = v_list[v_index]
v_index+=1
return ''.join(result)
The result: Time Limit Exceeded
And I found an extremely similar answer in the discussion:
def reverseVowels(s):
lst = list(s)
vowels_str = "aeiouAEIOU"
vowels_list = [item for item in lst if item in vowels_str]
vowels_list.reverse()
vowels_index = 0
for index, item in enumerate(lst):
if item in vowels_str:
lst[index] = vowels_list[vowels_index]
vowels_index += 1
return ''.join(lst)
The result: Accepted
This is so weird. I think these two code seem exactly the same.
The difference of them is nothing but parameters.
I am curious about why these codes cause distinct results.