I have string
hello
the vowels has to swap and the output is holle
e
and o
is swapped
Below is my code
vowels = ['a','e','i','o','u']
first_str = 'aiao'
l = list(first_str)
vowel_list = []
for vowel in l :
if vowel in vowels:
vowel_list.append(vowel)
for index,value in enumerate(l):
if value in vowels:
# print(value)
l[index] = vowel_list[-1]
vowel_list.remove(vowel_list[-1])
print(vowel_list)
''.join(l)
I got output oaai
Expected is also oaia
My Approach
- extract all vowels in list
- iterate over the string
- Swap the vowels while iterating from right side by putting [-1]
- After swap remove the element from the vowels list
edit courtesy @pranav using pop code is working ine
for index,value in enumerate(l):
if value in vowels:
l[index] = vowel_list.pop(-1)
''.join(l)
>Solution :
Here you go
vowels = "aeiou"
str = 'aiao'
str = list(str)
i = 0 ; j = len(str)-1
while i < j:
while i<j and str[i] not in v:
i += 1
while i<j and str[j] not in v:
j -= 1
str[i], str[j] = str[j], str[i]
i += 1
j -= 1
print("".join(str))
Approach : (Two Pointer Approach)
- Set two pointers(start and end of the string)
- Move the pointer until you find vowel
- Swap the characters at the pointers
- Repeat this until the pointers cross each other
Hope this solution helps