1. 程式人生 > >791. Custom Sort String - LeetCode

791. Custom Sort String - LeetCode

不存在 cte 出現 分享 shm 思路 9.png ret ets

Question

791. Custom Sort String

技術分享圖片

Solution

題目大意:給你字符的順序,讓你排序另一個字符串。

思路:

輸入參數如下:
S = "cba"
T = "abcd"

先構造一個map,sMap
key存儲S中出現的字符,value存儲字符在S中的位置
c -> 0
b -> 1
a -> 2

再構造一個int數組,sIdx
sIdx,存儲S中的字符在T字符串中出現的次數

遍歷T字符串
如果字符在sMap中,sIdx就加1
如果不存在,就直接加入到返回字符串

最後遍歷sIdx數組,將S中的字符加入到返回字符串

Java實現:

public String customSortString(String S, String T) {
    Map<Character, Integer> sMap = new HashMap<>();
    int[] sIdx = new int[S.length()];
    for (int i = 0; i < S.length(); i++) {
        sMap.put(S.charAt(i), i);
        sIdx[i] = 0;
    }

    String retStr = "";
    for (char c : T.toCharArray()) {
        if(sMap.containsKey(c)) {
            sIdx[sMap.get(c)] += 1;
            continue;
        };
        retStr += String.valueOf(c);
    }

    for (int i = 0; i < S.length(); i++) {
        while (sIdx[i]-- > 0) {
            retStr += S.charAt(i);
        }
    }
    return retStr;
}

791. Custom Sort String - LeetCode