Playing Hacks and Stuffs!
Given a string s, reverse only all the vowels in the string and return it.
The vowels are a, e, i, o, and u, and they can appear in both lower and upper cases, more than once.
My approach:
We know that we’ll be given a string s and our goal is to reverse only all the vowels in the string and return it
If you look at the example it’s more of they swap the vowels where it’s occurring in the left and right side of the string:
Input: s = "hello"
Output: "holle"
So I wrote a script to do the same thing and here’s what it does:
left and right which would hold the 0th and last index len(s)-1s[left] of the string is not a vowel I’ll make a while loop that checks for that and I’ll increment the left pointer by 1s[right] of the string is not a vowel I’ll make a while loop that checks for that and I’ll decrement the right pointer by 1s[left] and s[right] is vowel I’ll then swap them i.e set s[left], s[right] = s[right], s[left]left pointer by 1 and decrement the right pointer by 1 to keep the process going till I reach the condition where left > right then the loop finishesHere’s my solve script: link
class Solution:
def reverseVowels(self, s: str) -> str:
s = list(s)
vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
left, right = 0, len(s)-1
while left < right:
while left < right and s[left] not in vowels:
left += 1
while left < right and s[right] not in vowels:
right -= 1
if s[left] in vowels and s[right] in vowels:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
r = "".join(s)
return r