题目地址:
https://www.lintcode.com/problem/custom-sort-string/description
给定两个字符串 s s s和 t t t,题目保证两者都只含英文小写字母,并且 s s s里无重复字母。要求重排 t t t,使得 t t t的字母顺序是按照 s s s里字母顺序定义的。不在 s s s里的字母随便排在哪儿。返回任意一个重排的结果即可。
先统计一下 t t t的每个字母出现次数,以哈希表 c c c表示,然后再遍历 s s s,如果 s [ i ] s[i] s[i]出现了,则append到一个StringBuilder后面 c [ s [ i ] ] c[s[i]] c[s[i]]这么多次。最后再把没出现的字母也依次append到StringBuilder后面即可。代码如下:
public class Solution {
/**
* @param S: The given string S
* @param T: The given string T
* @return: any permutation of T (as a string) that satisfies this property
*/
public String customSortString(String S, String T) {
// Write your code here
int[] count = new int[26];
for (int i = 0; i < T.length(); i++) {
count[T.charAt(i) - 'a']++;
}
StringBuilder sb = new StringBuilder();
// 先处理S里有的字母
for (int i = 0; i < S.length(); i++) {
int idx = S.charAt(i) - 'a';
while (count[idx] > 0) {
sb.append((char) ('a' + idx));
count[idx]--;
}
}
// 再处理没有的
for (int i = 0; i < count.length; i++) {
if (count[i] == 0) {
continue;
}
for (int j = 0; j < count[i]; j++) {
sb.append((char) ('a' + i));
}
}
return sb.toString();
}
}
时空复杂度 O ( l t ) O(l_t) O(lt)。