0%

leetCode-451:Sort Characters By Frequency

问题描述

给定一个字符串,要求对字符串中的字符按出现次数大小进行排序。题目链接:点我

样例输入输出

输入:s = “tree”

输出:”eert” 或 “eetr”

输入:s = “Aabb”

输出:”bbaA” 或 “bbAa”

问题解法

先统计每个字符出现的次数,然后对字符按次数进行排序,最后输出排序后的字符(按数量输出)。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public String frequencySort(String s) {
class Node {
int count;
char ch;

Node(char ch) {
this.ch = ch;
count = 0;
}

void increase() {
count++;
}
}

Node[] nodes = new Node[62];
for (int i = 0; i < 62; i++) {
if (i < 26) {
nodes[i] = new Node((char) ('a' + i));
} else if (i < 52) {
nodes[i] = new Node((char) ('A' + i - 26));
} else {
nodes[i] = new Node((char) ('0' + i - 52));
}
}

for (char ch : s.toCharArray()) {
int index;
if (ch >= 'a' && ch <= 'z') {
index = ch - 'a';
} else if (ch >= 'A' && ch <= 'Z') {
index = ch - 'A' + 26;
} else {
index = ch - '0' + 52;
}

nodes[index].increase();
}

Arrays.sort(nodes, (x, y) -> y.count - x.count);

StringBuilder sb = new StringBuilder();
for (Node node : nodes) {
for (int i = 0; i < node.count; i++) {
sb.append(node.ch);
}
}

return sb.toString();
}
}