Sort the vowels in string s while keeping consonants in their original positions.
Input: s="lEetcOde" → Output: "lEOtcede"
Input: s="lYmpH" → Output: "lYmpH"
Extract vowels, sort them, then place back at vowel positions.
- Identify vowel positions and extract vowels
- Sort extracted vowels
- Place sorted vowels back at original vowel positions
- Return reconstructed string
public String sortVowels(String s) {
String vowels = "aeiouAEIOU";
List<Character> vowelList = new ArrayList<>();
char[] arr = s.toCharArray();
for (char c : arr) if (vowels.indexOf(c) >= 0) vowelList.add(c);
Collections.sort(vowelList);
int vi = 0;
for (int i = 0; i < arr.length; i++)
if (vowels.indexOf(arr[i]) >= 0) arr[i] = vowelList.get(vi++);
return new String(arr);
}
- Time Complexity: O(n log n)
- Space Complexity: O(n)