0%

791. Custom Sort String

O(m+n) time O(1) space
按照S的顺序把T中所有的字符重排即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string customSortString(string S, string T) {
int f[26] = {0};
for (char c : T) { // 先统计T中字母频数
++f[c - 'a'];
}
string s;
for (char c : S) {
s.append(f[c - 'a'], c); // 按照S中的顺序重排
f[c - 'a'] = 0; // 重排后频数清零
}
for (int i = 0; i < 26; ++i) {
s.append(f[i], 'a' + i); // 剩余没出现在S中的字母依次放到尾部即可
}
return s;
}
};