-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCustomSortString.java
More file actions
40 lines (32 loc) · 963 Bytes
/
CustomSortString.java
File metadata and controls
40 lines (32 loc) · 963 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
32
33
34
35
36
37
38
39
40
package string;
/**
* Description: https://leetcode.com/problems/custom-sort-string
* Difficulty: Medium
* Time complexity: O(m + n)
* Space complexity: O(n)
*/
public class CustomSortString {
public String customSortStringViaCountingSort(String order, String s) {
int[] freqMap = buildFreqMap(s);
StringBuilder sorted = new StringBuilder();
for (char c : order.toCharArray()) {
for (int i = 0; i < freqMap[c - 'a']; i++) {
sorted.append(c);
}
freqMap[c - 'a'] = 0;
}
for (char c = 'a'; c <= 'z'; c++) {
for (int i = 0; i < freqMap[c - 'a']; i++) {
sorted.append(c);
}
}
return sorted.toString();
}
private int[] buildFreqMap(String s) {
int[] freqMap = new int[26];
for (char c : s.toCharArray()) {
freqMap[c - 'a']++;
}
return freqMap;
}
}