791. 自定義字符串排序

字符串S和 T 只包含小寫字符。在S中,所有字符只會出現一次。

S 已經根據某種規則進行了排序。我們要根據S中的字符順序對T進行排序。更具體地說,如果Sxy之前出現,那麼返回的字符串中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
  • ST只包含小寫字符。

在真實的面試中遇到過這道題?


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);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章