LC.P791[自定义字符串排序]

方法一:计数模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public String customSortString(String order, String s) {
int[] cnt = new int[26];
for (int i = 0; i < s.length(); ++i) {
++cnt[s.charAt(i) - 'a'];
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < order.length(); ++i) {
char c = order.charAt(i);
while (cnt[c - 'a']-- > 0) builder.append(c);
}
for (int i = 0; i < 26; ++i) {
while (cnt[i]-- > 0) builder.append((char) (i + 'a'));
}
return builder.toString();
}
}
  • 时间复杂度:$O(m + n)$
  • 空间复杂度:$O(C)$,其中$C = 26$