[LeetCode Solutions] 791. Custom Sort String

題目

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

Example 1:
Input:  order = “cba”, s = “abcd”
Output:  “cbad”
Explanation: "a""b""c" appear in order, so the order of "a""b""c" should be "c""b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba""cdba""cbda" are also valid outputs.
Example 2:
Input:  order = “bcafg”, s = “abcd”
Output:  “bcad”
Explanation: The characters "b""c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order"b""c", and "a" from s should be arranged as "b""c""a""d" can be placed at any position since it’s not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b""c""a" maintain their order.
 

題目一開始看起來很可怕,但耐心看完之後就會這道題其實蠻簡單的,這道題簡單來說就是給你兩個String,order跟s,你要將s重新排列成order順序的字串。

以下先提供最直覺的解法。

public String customSortString(String order, String s) {
        List<Character> orderList = new ArrayList<>();
        List<Character> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();

        for(char c : order.toCharArray()){
            orderList.add(c);

            for(char c2 : s.toCharArray()){
                if(c == c2){
                    sb.append(c);
                }
            }
        }

        //s 去除 order的 字串
        for(char c : s.toCharArray()){
            if(!orderList.contains(c)){
                list.add(c);
            }
        }

         
       String sortedStr = sb.toString();
       for(int i=0; i<list.size(); i++){
           sortedStr += list.get(i);
       }

        return sortedStr;
    }

用陣列、ASCII來優化解法

public String customSortString(String order, String s) {
        StringBuilder sb = new StringBuilder();

        int[] freq = new int[26];
        for(int i=0; i<s.length(); i++){
            freq[s.charAt(i) - 'a']++;
        }

        for(int i=0; i<order.length(); i++){
            while(freq[order.charAt(i) - 'a'] > 0){
                sb.append(order.charAt(i));
                freq[order.charAt(i) - 'a'] --;

            }
        }

        for(int i=0; i<freq.length; i++){
            while(freq[i] > 0){
                sb.append((char)(i + 'a'));
                freq[i]--;
            }
        }

        return sb.toString();

    }

發佈留言