1. 程式人生 > >791. Custom Sort String字符串保持字母一樣,位置可以變

791. Custom Sort String字符串保持字母一樣,位置可以變

spa 異常 view int can 總結 解法 prope har

[抄題]:

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();
    }
}
View Code

791. Custom Sort String字符串保持字母一樣,位置可以變