791. Custom Sort String

SandTare strings composed of lowercase letters. InS, no letter occurs more than once.

Swas sorted in some custom order previously. We want to permute the characters ofTso that they match the order thatSwas sorted. More specifically, ifxoccurs beforeyinS, thenxshould occur beforeyin the returned string.

Return any permutation ofT(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.

Note:

  • S has length at most 26 , and no character is repeated in S .
  • T has length at most 200 .
  • S and T consist of lowercase letters only.
class Solution {
    public String customSortString(String S, String T) {
        Map<Character, Integer> hash = new HashMap<>();
        for (char c : T.toCharArray()){
            hash.put(c, hash.getOrDefault(c, 0) + 1);
        }

        StringBuilder sb = new StringBuilder();
        for (char c : S.toCharArray()){
            if (hash.containsKey(c)){
                for (int k = 0; k < hash.get(c); k++){
                    sb.append(c);
                }

                hash.put(c, 0);
            }
        }

        for (Character c : hash.keySet()){
            if (hash.get(c) > 0){
                for (int k = 0; k < hash.get(c); k++){
                    sb.append(c);    
                }
                hash.put(c, 0);
            }
        }

        return sb.toString();
    }
}

results for ""

    No results matching ""