-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCustomSortString
More file actions
31 lines (28 loc) · 920 Bytes
/
CustomSortString
File metadata and controls
31 lines (28 loc) · 920 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class CustomSortString {
public String customSortString(String order, String s) {
Map<Character, Integer> freqMap = new HashMap<>();
StringBuilder result = new StringBuilder();
// Store the frequency of each character in s
for (char c : s.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
// Append the characters from s in the order specified by order
for (char c : order.toCharArray()) {
if (freqMap.containsKey(c)) {
int freq = freqMap.get(c);
for (int i = 0; i < freq; i++) {
result.append(c);
}
freqMap.remove(c);
}
}
// Append any remaining characters from s
for (char c : freqMap.keySet()) {
int freq = freqMap.get(c);
for (int i = 0; i < freq; i++) {
result.append(c);
}
}
return result.toString();
}
}