題目
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.
Return any permutation of T (as a string) that satisfies this property.
答案
class Solution {
public String customSortString(String S, String T) {
int[] freq = new int[26];
StringBuilder sb = new StringBuilder();
for(char t : T.toCharArray()) {
freq[t - 'a']++;
}
for(char s : S.toCharArray()) {
for(int i = 0; i < freq[s - 'a']; i++)
sb.append(s);
freq[s - 'a'] = 0;
}
for(int i = 0; i < freq.length; i++) {
int f = freq[i];
for(int j = 0; j < f; j++)
sb.append((char)('a' + i));
}
return sb.toString();
}
}