字符串面试题:
找字符串中出现次数最多的字符,如果有多个这样字符,取第一个达到最大数目的字符
思路:遍历字符串,通过HashMap来记录字符以及出现次数,字符作key,次数作value。
再向HashMap中存在数据时,就比较当前遍历到的字符的出现次数是不是大于
当前最大的字符出现次数,是则替换,不是则继续遍历,直到遍历完整个字符串。
public class FindMaxCountChar {
public static char findCharMost(String str) {
HashMap<Character, Integer> map = new HashMap<>();
int max = 0;
char ans = ' ';
for(int i=0;i<str.length();i++){
if (!map.containsKey(str.charAt(i))) {
map.put(str.charAt(i), 1);
}else {
//value+1后,覆盖原来的元素
int count = map.get(str.charAt(i))+1;
map.put(str.charAt(i), count);
}
//如果出现次数大于当前最大,替换
if (map.get(str.charAt(i))>max) {
max = map.get(str.charAt(i));
ans = str.charAt(i);
}
}
return ans;
}
public static void main(String[] args) {
String str = "abcdefghijklba";
System.out.println(findCharMost(str));
}
}