Objective: Given a string, write an algorithm to replace all the vowels with next consonant, and if last alphabet is vowel, remove it.
Example:
String input: “abcdefg” Output: “bbcdffg” String input: “aaaabccceee” Output: “bbbbbccc” String input: “aaa” Output: “”
Approach:
- Traverse the string right to left one character at a time.
- Maintain a variable , last_visited_non_vowel
- During traversal , when vowel is encountered, replace it with , last_visited_non_vowel and add to result.
- During traversal , when consonant(non vowel) is encountered, update the last_visited_non_vowel and add to result.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ReplaceVowels { | |
public String replaceVowels(String input){ | |
String result = ""; | |
char last_visited_non_vowel = '\0'; | |
for (int i = input.length()–1; i>=0 ; i—) { | |
char x = input.charAt(i); | |
if(isVowel(x)){ | |
if(last_visited_non_vowel!='\0') { | |
result = String.valueOf(last_visited_non_vowel) + result; | |
} | |
}else{ | |
last_visited_non_vowel = x; | |
result = String.valueOf(x) + result; | |
} | |
} | |
return result; | |
} | |
public boolean isVowel(char x){ | |
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u' | |
||x=='A'||x=='E'||x=='I'||x=='O'||x=='U') | |
return true; | |
else | |
return false; | |
} | |
public static void main(String[] args) { | |
ReplaceVowels r = new ReplaceVowels(); | |
String input = "abcdefg"; | |
System.out.println("Input: " + input + ", Output: " + r.replaceVowels(input)); | |
input = "aaaabccceee"; | |
System.out.println("Input: " + input + ", Output: " + r.replaceVowels(input)); | |
input = "aaaa"; | |
System.out.println("Input: " + input + ", Output: " + r.replaceVowels(input)); | |
} | |
} |
Output:
Input: abcdefg, Output: bbcdffg Input: aaaabccceee, Output: bbbbbccc Input: aaaa, Output: