[LeetCode] 451. Sort Characters By Frequency 解题报告

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

这一题为medium难度,但是个人感觉比较简单,可以说的不多,很显然是遍历统计次数,然后输出即可,直接上思路。

方法:

遍历整个单词,对于每个字母统计出现的顺序。针对每个字母,我使用的是一个int[][]来存储。对于一个字符,int[0]存储的是它出现的次数,遇到一次就++,int[1]存储的是该字符的index,这是为了在后面对频率排序的时候,仍然知道对应频率的字符是哪一个。(其实这个地方就是一个key value对,但是为了在结果里面排名更靠前,使用array无疑是最快的)。

遍历完以后,针对int[0]降序排列,然后按照int[1]字符,int[0]的频率,输出即可,很简单。

下面是代码,复杂度为O(n),实际运行时间大致在n到2n之间:


public class Solution {
    public String frequencySort(String s) {
        char[] cArr = s.toCharArray();
        // int[][]={freq,index}
        int[][] nArrAlphas = new int[128][2];
        for (int i = 0; i < nArrAlphas.length; i++) {
            nArrAlphas[i][1] = i;
        }
        for (char c : cArr) {
            nArrAlphas[c][0]++;
        }
        Arrays.sort(nArrAlphas, new Comparator<int[]>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[0] - o1[0];
            }
        });
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < nArrAlphas.length; i++) {
            if (nArrAlphas[i][0] > 0) {
                for (int j = 0; j < nArrAlphas[i][0]; j++) {
                    sb.append((char) nArrAlphas[i][1]);
                }
            } else {
                break;
            }
        }
        return sb.toString();

    }
}
实际上,在new int[][]的时候,可打印的字符应该不会多到128个,实际上应该少于这个值,我偷懒就直接写了128。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值