找出字符串中出现次数最多的字母

我这个人,一般现场做或者线上做面试题,表现都很差,但是給我一个IDE,我就起飞了,面向IDE编程的选手。

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
package com.alonelaval.java.leetcode;
/**
* @author huawei
* @create 2019-11-28
**/
public class AsciiTest {
/**
* 找出字符串中出现次数最多的字母,次数相同的情况下返回ascii code更小的,没有字母的话返回null(忽略大小写,统一当成小写处理).
*
* <p>
* 提示:
* 1. 字符串长度在1000以内,且只包含ascii字符
* </p>
*
* @param string 只包含ascii字符的字符串.
* @return 出现次数最多的字母.
*/
public static Character countStr(String str ) {
if(str == null ) {
return null;
}
int results []= new int[128];
int c = 0;
int maxValue=0;
for(int i=0; i < str.length();i++){
int a = str.charAt(i);
if(results[a]+1 > maxValue){
maxValue = results[a]+1;
c = a;
}else if(results[a] == maxValue && c < a){
c= a;
}
results[a]=results[a]+1;
}
return (char)c;
}
public static void main(String[] args) {
String str="12122";
System.out.println(countStr(str));
}
}