|
1 | 1 | package org.sean.sorting; |
2 | 2 |
|
3 | | -import java.util.Arrays; |
4 | | -import java.util.HashMap; |
5 | | -import java.util.Map; |
6 | | -import java.util.TreeMap; |
7 | | - |
8 | 3 | // 791. Custom Sort String |
9 | 4 | 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; |
12 | 8 |
|
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 | + } |
16 | 13 |
|
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++) { |
20 | 16 | 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 | + } |
25 | 22 |
|
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; |
39 | 24 | } |
40 | 25 | } |
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 | + } |
47 | 33 | } |
48 | 34 | } |
49 | | - return sorted + rest.toString(); |
| 35 | + |
| 36 | + return builder.toString(); |
50 | 37 | } |
51 | 38 | } |
0 commit comments