forked from super30admin/Strings-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomSortString.java
More file actions
38 lines (28 loc) · 1.09 KB
/
Copy pathCustomSortString.java
File metadata and controls
38 lines (28 loc) · 1.09 KB
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
32
33
34
35
36
37
38
/**
* Time Complexity: O(n + m) where n is length of s and m is length of order.
* Space Complexity: O(1) (since the map has at most 26 entries, constant-size alphabet).
*/
class Solution {
public String customSortString(String order, String s) {
StringBuilder tempResult = new StringBuilder();
Map<Character, Integer> frequencyInS = new HashMap<>();
for (char ch : s.toCharArray()) {
frequencyInS.put(ch, frequencyInS.getOrDefault(ch, 0) + 1);
}
for (int i = 0; i < order.length(); i++) {
if (frequencyInS.containsKey(order.charAt(i))) {
int numOfTimesInS = frequencyInS.get(order.charAt(i));
for (int j = 0; j < numOfTimesInS; j++) {
tempResult.append(order.charAt(i));
}
frequencyInS.remove(order.charAt(i));
}
}
for (char ch : frequencyInS.keySet()) {
for (int j = 0; j < frequencyInS.get(ch); j++) {
tempResult.append(ch);
}
}
return tempResult.toString();
}
}