Skip to content

Latest commit

 

History

History
82 lines (62 loc) · 2.21 KB

_791. Custom Sort String.md

File metadata and controls

82 lines (62 loc) · 2.21 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 24, 2024

Last updated : June 24, 2024


Related Topics : Hash Table, String, Sorting

Acceptance Rate : 70.901 %


Solutions

Java

class Solution {
    public String customSortString(String order, String s) {
        HashMap<Character, Integer> reference = new HashMap<>();
        for (int i = 0; i < order.length(); i++) {
            reference.put(order.charAt(i), i);
        }

        Character[] output = new Character[s.length()];
        for (int i = 0; i < s.length(); i++) {
            output[i] = s.charAt(i);
        }

        Arrays.sort(output, (a, b) -> reference.getOrDefault(a, Integer.MAX_VALUE) - reference.getOrDefault(b, Integer.MAX_VALUE));

        StringBuilder sb = new StringBuilder();

        for (char c : output) {
            sb.append(c);
        }

        return sb.toString();
    }
}
class Solution {
    public String customSortString(String order, String s) {
        int[] charCounter = new int[26];

        for (char c : s.toCharArray()) {
            charCounter[c - 'a']++;
        }

        StringBuilder sb = new StringBuilder();
        for (char c : order.toCharArray()) {
            for (int i = 0; i < charCounter[c - 'a']; i++) {
                sb.append(c);
            }
            charCounter[c - 'a'] = 0;
        }

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

        return sb.toString();
    }
}