帮我写一个java面试的题目
时间: 2023-07-28 09:10:34 浏览: 48
好的,这是一个 Java 面试题目:
写一个程序,找出一个字符串中出现次数最多的字符和出现的次数。
例如,对于字符串 "hello world",程序应该输出 "l" 出现了 3 次。
以下是可能的 Java 代码实现:
```java
public class Main {
public static void main(String[] args) {
String str = "hello world";
int[] count = new int[256];
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
count[c]++;
}
int maxCount = 0;
char maxChar = ' ';
for (int i = 0; i < count.length; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maxChar = (char) i;
}
}
System.out.println("最多出现的字符是:" + maxChar + ",出现了 " + maxCount + " 次。");
}
}
```
这个程序使用了一个长度为 256 的整数数组来记录每个字符出现的次数,然后遍历数组找到出现次数最多的字符和次数。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)