Skip to content

Commit 393e998

Browse files
authored
Create 2785-sort-vowels-in-a-string.java
1 parent 67ceafe commit 393e998

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/**
2+
* Problem: Sort Vowels in a String
3+
* LeetCode Link: https://leetcode.com/problems/sort-vowels-in-a-string/
4+
*
5+
* Given a string s, sort only the vowels in ascending order and keep other characters in place.
6+
*
7+
* Approach 1:
8+
* - Extract vowels by checking "AEIOUaeiou".indexOf(c).
9+
* - Sort the extracted vowels.
10+
* - Rebuild the string by replacing vowels in order.
11+
*
12+
* Approach 2:
13+
* - Use a Set<Character> of vowels for O(1) lookup.
14+
* - Extract vowels into a list.
15+
* - Sort the list.
16+
* - Reconstruct the string by replacing vowels from the sorted list.
17+
*
18+
* Time Complexity (both approaches): O(n log n)
19+
* - O(n) to extract vowels.
20+
* - O(k log k) to sort vowels (k ≤ n).
21+
* - O(n) to rebuild the string.
22+
*
23+
* Space Complexity (both approaches): O(n)
24+
* For storing the extracted vowels and the result string.
25+
*/
26+
27+
class Solution {
28+
29+
// Approach 1
30+
public String sortVowelsApproach1(String s) {
31+
List<Character> vowels = new ArrayList<>();
32+
33+
// Extract vowels
34+
for (char c : s.toCharArray()) {
35+
if ("AEIOUaeiou".indexOf(c) != -1) {
36+
vowels.add(c);
37+
}
38+
}
39+
40+
// Sort vowels
41+
Collections.sort(vowels);
42+
43+
// Rebuild string with sorted vowels
44+
StringBuilder result = new StringBuilder();
45+
int vIndex = 0;
46+
for (char c : s.toCharArray()) {
47+
if ("AEIOUaeiou".indexOf(c) != -1) {
48+
result.append(vowels.get(vIndex++));
49+
} else {
50+
result.append(c);
51+
}
52+
}
53+
54+
return result.toString();
55+
}
56+
57+
// Approach 2
58+
public String sortVowelsApproach2(String s) {
59+
Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
60+
List<Character> extractedVowels = new ArrayList<>();
61+
62+
// Extract vowels
63+
for (char c : s.toCharArray()) {
64+
if (vowels.contains(c)) {
65+
extractedVowels.add(c);
66+
}
67+
}
68+
69+
// Sort vowels
70+
Collections.sort(extractedVowels);
71+
72+
// Rebuild string with sorted vowels
73+
StringBuilder sb = new StringBuilder();
74+
int index = 0;
75+
for (char c : s.toCharArray()) {
76+
if (vowels.contains(c)) {
77+
sb.append(extractedVowels.get(index++));
78+
} else {
79+
sb.append(c);
80+
}
81+
}
82+
83+
return sb.toString();
84+
}
85+
}

0 commit comments

Comments
 (0)