📅  最后修改于: 2023-12-03 15:06:08.803000             🧑  作者: Mango
| | 问题 3 是一种常见的编程题型,通常涉及到字符串处理、数组操作和逻辑运算。在该问题中,输入一个字符串或数组,需要找到其中出现最多的数字或字母,并输出该数字或字母及其出现次数。
使用HashMap是解决该问题的常用方法,具体步骤如下:
该方法的时间复杂度为 O(n),空间复杂度为 O(n)。
另一种解决该问题的方法是使用桶排序,具体步骤如下:
该方法的时间复杂度为 O(n),空间复杂度为 O(k),其中 k 为数字或字母的种类数。
public static char findMostCommonChar(String str) {
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
char res = ' ';
int max = 0;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
int freq = entry.getValue();
if (freq > max) {
max = freq;
res = entry.getKey();
}
}
return res;
}
def find_most_common_char(s):
count = [0] * 256
for c in s:
count[ord(c)] += 1
max_count = 0
res = ' '
for i in range(256):
if count[i] > max_count:
max_count = count[i]
res = chr(i)
return res
char findMostCommonChar(string str) {
vector<int> count(256, 0);
for (char c : str) {
count[c]++;
}
int max_count = 0;
char res = ' ';
for (int i = 0; i < 256; i++) {
if (count[i] > max_count) {
max_count = count[i];
res = i;
}
}
return res;
}
以上代码仅为示例,具体实现可能因语言和场景的不同而有所改变,实际使用时需根据具体情况进行调整。