Sort an input string using an arbitrary alphabet

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sort an input string using an arbitrary alphabet相关的知识,希望对你有一定的参考价值。

For example: custom alphabet: xyzabc
input to sort according to custom alphabet: cyxz
output according to custom alphabet: xyzc .
因为alphabet有限,可以 bucket sort,将alph存进map,设alpg 度为m,输 度n,那么空间

O(M), 时间max(m ,n 或者直接存 26个字 表的bucket,然后找找alph的顺序输出。空间26,时间 样

解法1:

public String changeAlph(String alph, String word) {
        int[] bucket = new int[26];
        for (char c : word.toCharArray()) {
            bucket[c - ‘a‘]++;
        }
        StringBuilder sb = new StringBuilder();
        for (char c : alph.toCharArray()) {
            while (bucket[c - ‘a‘]-- > 0) sb.append(c);
        }
        return sb.toString();
    }

    解法2:

    public String changeAlph(String alph, String word) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : word.toCharArray()) {
            if (!map.containsKey(c)) map.put(c, 0);
            map.put(c, map.get(c) + 1);
        }
        StringBuilder sb = new StringBuilder();
        for (char c : alph.toCharArray()) {
            if (map.containsKey(c)) {
                for (int i = 0; i < map.get(c); i++) sb.append(c);
            }
        }
        return sb.toString();
    }

  

以上是关于Sort an input string using an arbitrary alphabet的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-912.Sort an Array

[LeetCode] 912. Sort an Array 数组排序

Insertion sort

leetcode 451. Sort Characters By Frequency

Kickstart试水

[Algorithms] Sort an Array with a Nested for Loop using Insertion Sort in JavaScript