解题思路
这是一个字符统计和排序问题。需要统计字符串中每个字符出现的次数,并按照以下规则排序:
- 按照字符出现次数由多到少排序
- 如果出现次数相同,则按照ASCII码由小到大排序
关键点
-
输入规则:
- 字符串长度:
- 只包含小写英文字母和数字
- 字符串长度:
-
处理要求:
- 统计每个字符出现次数
- 按照出现次数降序排序
- 出现次数相同时按ASCII码升序排序
代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string str;
while (cin >> str) {
// 统计每个字符出现次数
vector<pair<char, int>> counts;
vector<bool> visited(128, false); // ASCII码范围
for (char c : str) {
if (!visited[c]) {
visited[c] = true;
int count = 0;
for (char ch : str) {
if (ch == c) count++;
}
counts.push_back({c, count});
}
}
// 排序:先按次数降序,次数相同按ASCII码升序
sort(counts.begin(), counts.end(),
[](const pair<char, int>& a, const pair<char, int>& b) {
if (a.second != b.second) return a.second > b.second;
return a.first < b.first;
});
// 输出结果
string result;
for (const auto& p : counts) {
result += p.first;
}
cout << result << endl;
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
// 统计每个字符出现次数
Map<Character, Integer> countMap = new HashMap<>();
for (char c : str.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
// 转换为列表便于排序
List<Map.Entry<Character, Integer>> list =
new ArrayList<>(countMap.entrySet());
// 排序:先按次数降序,次数相同按ASCII码升序
Collections.sort(list, (a, b) -> {
if (!a.getValue().equals(b.getValue())) {
return b.getValue() - a.getValue();
}
return a.getKey() - b.getKey();
});
// 输出结果
StringBuilder result = new StringBuilder();
for (Map.Entry<Character, Integer> entry : list) {
result.append(entry.getKey());
}
System.out.println(result.toString());
}
}
}
while True:
try:
s = input()
# 统计每个字符出现次数
char_count = {}
for c in s:
char_count[c] = char_count.get(c, 0) + 1
# 按照次数和ASCII码排序
sorted_chars = sorted(char_count.items(),
key=lambda x: (-x[1], x[0]))
# 输出结果
result = ''.join(char for char, _ in sorted_chars)
print(result)
except:
break
算法及复杂度
算法分析
-
统计过程:
- 遍历字符串统计每个字符出现次数
- 使用哈希表或数组存储统计结果
-
排序过程:
- 自定义排序规则
- 先按出现次数降序
- 次数相同时按ASCII码升序
复杂度分析
- 时间复杂度:
- 其中
是不同字符的数量,主要是排序的复杂度
- 空间复杂度:
-
是字符集大小(这里是128,常数空间)