Description:
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.
Example :
Input:
S = "cba"
T = "abcd"
Output: "cbad"
Explanation:
“a”, “b”, “c” appear in S, so the order of “a”, “b”, “c” should be “c”, “b”, and “a”.
Since “d” does not appear in S, it can be at any position in T. “dcba”, “cdba”, “cbda” are also valid outputs.
Note:
- S has length at most 26, and no character is repeated in S.
- T has length at most 200.
- S and T consist of lowercase letters only.
题意:给定一个字符串S定义了各个小写字母排序时的顺序(例如字符串“cab”,则排序后c应当出现在a前面,a出现在b前面);根据给定的字符串S返回字符串T排序后的字符串,其中在S中没有出现的字符串可以按照任何顺序排列;需要注意的是T中可能会有重复的元素;
解法:因为S定义了字母的排列顺序,我们就不可以直接利用ASCLL码比较来进行排序;不过,我们可以用一个数组自定义我们自己的ASCLL码;首先,我们将字符串S中出现的字母按照出现的先后顺序指定大小(从小到大);其次,在S中没有出现的字母,可以随意指定大于S长度的大小,但每个大小应当不一样;
例如:
字符串S=“cba”
字符串T=“abcd”
用数组table来保存各个字母的ASCLL码大小
首先定义字符串S中已经有的,得到:
数组 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
table | 3 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
其次,将字符串S中没有出现的,可以随意指定大于S长度的大小,这里我们就用S的长度依次增长,得到:
数组 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
table | 3 | 2 | 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
排序时我们就可以直接利用上表得到新的字符串的排序;
Java
class Solution {
public String customSortString(String S, String T) {
int[] table = new int[26];
int len = S.length();
StringBuilder result = new StringBuilder();
//get ASCLL
for (int i = 0; i < 26; i++) {
if (i < S.length()) {
table[S.charAt(i) - 'a'] = i + 1;
}
table[i] = table[i] == 0 ? ++len : table[i];
}
result.append(T.charAt(0));
for (int i = 1; i < T.length(); i++) {
int index = 0;
for (; index < i; index++) {
if (table[T.charAt(i) - 'a'] <= table[result.charAt(index) - 'a']) break;
}
result.insert(index, T.charAt(i));
}
return result.toString();
}
}