Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to swap the vowles between in the strings

I have string

hello the vowels has to swap and the output is holle e and o is swapped

Below is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

  1. extract all vowels in list
  2. iterate over the string
  3. Swap the vowels while iterating from right side by putting [-1]
  4. 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)

  1. Set two pointers(start and end of the string)
  2. Move the pointer until you find vowel
  3. Swap the characters at the pointers
  4. Repeat this until the pointers cross each other

Hope this solution helps

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading