字符串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);
}
}