Given a string with lowercase English alphabets. The task is to replace all the consonants in the string with the nearest vowels. If a consonant is near to two vowels then replace it with the one that comes first in English alphabets.
Note: Vowels already present in the string must be left as it is.
Input : str = "geeksforgeeks" Output : eeeiueooeeeiu Input : str = "gfg" Output : eee
A simple approach is to compare the consonant with vowels to determine the nearest vowel. First, check if the consonant falls between two vowels. If it falls between 2 vowels then find the absolute difference between the ASCII value of consonant with the ASCII value of both vowels.
Replace it with that vowel, with which the absolute difference is minimum.
However, if the ASCII code of consonant does not fall between two vowels, then the consonant can be ‘v’, ‘w’, ‘x’, ‘y’, ‘z’. Hence, the answer is ‘u’ in this case.
Below is the implementation of the above approach:
A better approach is to make an array of size 26 that stores nearest vowel for every character.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.