字符串S
和 T
只包含小写字符。在S
中,所有字符只会出现一次。
S
已经根据某种规则进行了排序。我们要根据S
中的字符顺序对T
进行排序。更具体地说,如果S
中x
在y
之前出现,那么返回的字符串中x
也应出现在y
之前。
返回任意一种符合条件的字符串T
。
示例: 输入: S = "cba" T = "abcd" 输出: "cbad" 解释: S中出现了字符 "a", "b", "c", 所以 "a", "b", "c" 的顺序应该是 "c", "b", "a". 由于 "d" 没有在S中出现, 它可以放在T的任意位置. "dcba", "cdba", "cbda" 都是合法的输出。
注意:
S
的最大长度为26
,其中没有重复的字符。T
的最大长度为200
。S
和T
只包含小写字符。
在真实的面试中遇到过这道题?
class Solution {
public String customSortString(String S, String T) {
int[] rec = new int[123];
for(int i=1;i<=S.length();i++){
rec[S.charAt(i-1)] = i;
}
char[] res = new char[T.length()];
int lastIdx = res.length -1 ;
int[] p = new int[27];
for(int i=0;i<res.length;i++){
int temp = rec[T.charAt(i)];
if(temp==0){
res[lastIdx--] = T.charAt(i);
}else{
p[temp]++;
}
}
for(int i = 1,x=0;i<27;i++){
int p1 = p[i];
if(p1!=0){
while(p1-->0){
res[x++] = S.charAt(i-1);
}
}else{
break;
}
}
return new String(res);
}
}