1. 程式人生 > >Sort an input string using an arbitrary alphabet

Sort an input string using an arbitrary alphabet

section return map ret layout put sort col sin

For example: custom alphabet: xyzabc
input to sort according to custom alphabet: cyxz
output according to custom alphabet: xyzc .
因為alphabet有限,可以 bucket sort,將alph存進map,設alpg 度為m,輸 度n,那麽空間

O(M), 時間max(m ,n 或者直接存 26個字 表的bucket,然後找找alph的順序輸出。空間26,時間 樣

解法1:

public String changeAlph(String alph, String word) {
        int[] bucket = new int[26];
        for (char c : word.toCharArray()) {
            bucket[c - ‘a‘]++;
        }
        StringBuilder sb = new StringBuilder();
        for (char c : alph.toCharArray()) {
            while (bucket[c - ‘a‘]-- > 0) sb.append(c);
        }
        return sb.toString();
    }

    解法2:

    public String changeAlph(String alph, String word) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : word.toCharArray()) {
            if (!map.containsKey(c)) map.put(c, 0);
            map.put(c, map.get(c) + 1);
        }
        StringBuilder sb = new StringBuilder();
        for (char c : alph.toCharArray()) {
            if (map.containsKey(c)) {
                for (int i = 0; i < map.get(c); i++) sb.append(c);
            }
        }
        return sb.toString();
    }

  

Sort an input string using an arbitrary alphabet