Problem Statement
Given a string s, rearrange the characters such that all vowels appear at the beginning, while maintaining the relative order of the consonants. The order of vowels should also remain the same as in the original string.
Example 1
Input: "automation"
Output: "auaotmtn"
Example 2
Input: "hello"
Output: "eo hll"
Example 3
Input: "java"
Output: "aa jv"
Solution Approach
Extract vowels in order.
Extract consonants in order.
Concatenate vowels + consonants to form the result.
You can find the video here
Java Solution
public class MoveVowelsToLeft {
public static String moveVowelsToLeft(String s) {
StringBuilder vowels = new StringBuilder();
StringBuilder consonants = new StringBuilder();
for (char c : s.toCharArray()) {
if (isVowel(c)) {
vowels.append(c);
} else {
consonants.append(c);
}
}
return vowels.append(consonants).toString();
}
private static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
public static void main(String[] args) {
System.out.println(moveVowelsToLeft("automation")); // Output: auaotmtn
System.out.println(moveVowelsToLeft("hello")); // Output: eo hll
System.out.println(moveVowelsToLeft("java")); // Output: aa jv
}
}
Time Complexity Analysis
O(n), where n is the length of the string (single pass to classify characters, another pass to concatenate).
No comments:
Post a Comment