700591. Arrange Consonants and Vowels
Arrange Consonants and Vowels
Summary
Given a string, arrange all consonants followed by all vowels. The string may contain spaces and punctuation marks, which should be ignored. This problem involves manipulating a string and identifying consonants and vowels.
Detailed Explanation
The approach to this problem is to iterate through the given string, identify consonants and vowels, and then rearrange them accordingly. A simple way to do this is by maintaining two pointers, one for consonants and one for vowels. Initialize two linked lists: one for consonants and one for vowels.
Here's a step-by-step breakdown of the solution:
- Create an empty linked list for consonants (
consonantList) and another for vowels (vowelList). - Iterate through the given string:
- Check if the current character is a consonant (using ASCII values or a helper function). If it's a consonant, add it to
consonantList. - Check if the current character is a vowel (using ASCII values or a helper function). If it's a vowel, add it to
vowelList.
- Check if the current character is a consonant (using ASCII values or a helper function). If it's a consonant, add it to
- After iterating through the entire string, concatenate the
consonantListandvowelListto form the final output string.
The time complexity of this solution is O(n), where n is the length of the input string. The space complexity is also O(n) due to the creation of the linked lists.
Optimized Solutions
Here are optimized solutions in various programming languages:
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
String str = "Hello World";
String consonants = "";
String vowels = "";
for (char c : str.toCharArray()) {
if (!isVowel(c)) {
consonants += c;
} else {
vowels += c;
}
}
System.out.println(consonants + vowels);
}
public static boolean isVowel(char c) {
c = Character.toLowerCase(c);
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
}