Custom Sort String

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.

LeetCode Problem - 791

class Solution {
    // This method custom sorts the string `s` based on the order specified in `order`.
    public String customSortString(String order, String s) {
        // HashMap to store the frequency of each character in the string `s`
        HashMap<Character, Integer> freq = new HashMap<>();

        // Count the frequency of each character in the string `s`
        for (int i = 0; i < s.length(); i++) {
            char letter = s.charAt(i);
            freq.put(letter, freq.getOrDefault(letter, 0) + 1);
        }

        // StringBuilder to build the custom sorted string
        StringBuilder sb = new StringBuilder();

        // Append characters in the order specified in `order`
        for (char letter : order.toCharArray()) {
            if (freq.containsKey(letter)) {
                sb.append(String.valueOf(letter).repeat(freq.get(letter)));
                // Remove the character from the frequency map after appending
                freq.remove(letter);
            }
        }

        // Append remaining characters in `s` that are not in `order`
        for (char letter : freq.keySet()) {
            sb.append(String.valueOf(letter).repeat(freq.get(letter)));
        }

        // Return the custom sorted string
        return sb.toString();
    }
}