[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
大体思路是对的:先差后s,但是还可以优化一下:先s后差。
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
粘贴差字母的时候,从26个字母a-z逐个入手即可。
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
粘贴差字母的时候,从26个字母a-z逐个入手即可。
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class Solution {
public String customSortString(String S, String T) {
//corner case
if (S == null || T == null) return ""; //initialization: int[26], count char
int[] count = new int[26];
for (char t : T.toCharArray()) {
count[t - 'a']++;
} StringBuilder sb = new StringBuilder();
//append s
for (char s : S.toCharArray()) {
while (count[s - 'a']-- > 0)
sb.append(s);
} //append t - s from a to z
for (char c = 'a'; c <= 'z'; c++) {
while (count[c - 'a']-- > 0)
sb.append(c);
} return sb.toString();
}
}