Skip to content

Commit 4ba4ef5

Browse files
committed
Refine the solution for LC #791
1 parent 55ae1e7 commit 4ba4ef5

File tree

1 file changed

+24
-37
lines changed

1 file changed

+24
-37
lines changed
Lines changed: 24 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,38 @@
11
package org.sean.sorting;
22

3-
import java.util.Arrays;
4-
import java.util.HashMap;
5-
import java.util.Map;
6-
import java.util.TreeMap;
7-
83
// 791. Custom Sort String
94
public class CustomSort {
10-
public String customSortString(String order, String str) {
11-
if (order == null || order.isEmpty() || str == null || str.isEmpty()) return str;
5+
public String customSortString(String order, String s) {
6+
if (s.length() == 1)
7+
return s;
128

13-
// Index mapping
14-
int[] positions = new int['z' - 'a' + 1];
15-
Arrays.fill(positions, -1);
9+
int[] charCnt = new int[26];
10+
for (int i = 0; i < s.length(); i++) {
11+
charCnt[s.charAt(i) - 'a'] += 1;
12+
}
1613

17-
Map<Integer, Character> posCharMap = new HashMap<>();
18-
int orderLen = order.length();
19-
for (int i = 0; i < orderLen; i++) {
14+
StringBuilder builder = new StringBuilder();
15+
for (int i = 0; i < order.length(); i++) {
2016
char ch = order.charAt(i);
21-
positions[ch - 'a'] = i;
22-
23-
posCharMap.put(i, ch);
24-
}
17+
int cnt = charCnt[ch - 'a'];
18+
if (cnt > 0) {
19+
for (int j = 0; j < cnt; j++) {
20+
builder.append(ch);
21+
}
2522

26-
// <Pos, count>
27-
TreeMap<Integer, Integer> map = new TreeMap<>();
28-
StringBuilder sorted = new StringBuilder();
29-
StringBuilder rest = new StringBuilder();
30-
int len = str.length();
31-
for (int j = 0; j < len; j++) {
32-
char c = str.charAt(j);
33-
int position = positions[c - 'a'];
34-
if (position < 0) {
35-
rest.append(c);
36-
} else {
37-
if (map.containsKey(position)) map.put(position, map.get(position) + 1);
38-
else map.put(position, 1);
23+
charCnt[ch - 'a'] = 0;
3924
}
4025
}
41-
42-
for (int pos : map.keySet()) {
43-
int cnt = map.get(pos);
44-
char ch = posCharMap.get(pos);
45-
for (int i = 0; i < cnt; i++) {
46-
sorted.append(ch);
26+
for (int i = 0; i < charCnt.length; i++) {
27+
char ch = (char) ('a' + i);
28+
int cnt = charCnt[i];
29+
if (cnt > 0) {
30+
for (int j = 0; j < cnt; j++) {
31+
builder.append(ch);
32+
}
4733
}
4834
}
49-
return sorted + rest.toString();
35+
36+
return builder.toString();
5037
}
5138
}

0 commit comments

Comments
 (0)