您的位置:首页 > 产品设计 > UI/UE

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

2017-03-07 07:02 211 查看
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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode