> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/05-15-2022-791.-custom-sort-string.md).

# 05/15/2022 791. Custom Sort String

String order, String s

You are given two strings order and s. All the words 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*.

For example:

order: cdab

s: abbcdef

return: cdabbef

Solution 1: use hashmap

```
// Some code
class Solution {
    public String customSortString(String order, String s) {
        
        HashMap<Character, Integer> map = new HashMap<>();
        for (char ch: s.toCharArray()){
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }
        
        StringBuilder sb = new StringBuilder();
        for (char ch: order.toCharArray()){
              if (map.containsKey(ch)){
                  int fre = map.get(ch);
                  for (int i = 0; i < fre; i++){
                      sb.append(ch);
                  }     
                  map.remove(ch);
            }
               
        }   
        if (sb.length() < s.length()){
            for (char ch: s.toCharArray()){
                if (map.containsKey(ch))
                    sb.append(ch);   
            }
        
        }
        
            
        
        return sb.toString();
        

    }
}
```

```
// Some code
class Solution {
    public String customSortString(String order, String s) {
        
        int[] letters = new int[26];
        for (char ch: s.toCharArray()){
            letters[ch - 'a']++;
        }
        
        
        StringBuilder sb = new StringBuilder();
        for (char ch: order.toCharArray()){
            for (int i = 0; i < letters[ch - 'a']; i++){
                sb.append(ch);
            }
            letters[ch-'a'] = 0;// because we don't need it anymore, we need to set it to 0;
        }
        
        for (char c = 'a'; c <= 'z'; c++){// need to remember this.
            for (int i = 0; i < letters[c - 'a']; i++){
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
```
