leetcode-791-Custom-Sort-String

描述


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.

1
2
3
4
5
6
7
8
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 和 T,要求 T 按照 S 的顺序进行排序,T 的 S 中没有出现的字母不作要求。可以通过 HashMap 的结构统计 T 中每个字母出现的次数,然后遍历 S,按照 S 中的字母的顺序构造新的 T,重复该字母出现的次数,然后将其置为 0,最后重复一遍相同的步骤,将 T 中的其他字母也按该方法加入新 T 即可。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public String customSortString(String S, String T) {
String result = "";
int[] charFreq = new int[26];
for (int i = 0; i < T.length(); i++) {
charFreq[T.charAt(i)-'a']++;
}
for (int i = 0; i < S.length(); i++) {
while(charFreq[S.charAt(i)-'a'] > 0) {
charFreq[S.charAt(i)-'a']--;
result += S.charAt(i);
}
}
for (int i = 0; i < T.length(); i++) {
while(charFreq[T.charAt(i)-'a'] > 0) {
charFreq[T.charAt(i)-'a']--;
result += T.charAt(i);
}
}
return result;
}
}

解决方案2(Javascript)

评论区里有一个回帖,利用 Javascript 里的 sort 方法进行排序,一行代码就能解决问题。

1
2
3
4
5
6
7
8
/**
* @param {string} S
* @param {string} T
* @return {string}
*/
var customSortString = function(S, T) {
return T.split('').sort((a, b) => S.indexOf(a)-S.indexOf(b)).join('')
};

如果是使用箭头函数:

1
2
3
4
5
6
/**
* @param {string} S
* @param {string} T
* @return {string}
*/
var customSortString = (S, T) => T.split('').sort((a, b) => S.indexOf(a)-S.indexOf(b)).join('')

题目来源