目录
题目
3303. 单词分析 - AcWing题库https://www.acwing.com/problem/content/3306/
代码
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String s = input.nextLine();
int[] count = new int[26];
Map<Character,Integer> map = new HashMap<>();
map.put('a',0);
map.put('b',1);
map.put('c',2);
map.put('d',3);
map.put('e',4);
map.put('f',5);
map.put('g',6);
map.put('h',7);
map.put('i',8);
map.put('j',9);
map.put('k',10);
map.put('l',11);
map.put('m',12);
map.put('n',13);
map.put('o',14);
map.put('p',15);
map.put('q',16);
map.put('r',17);
map.put('s',18);
map.put('t',19);
map.put('u',20);
map.put('v',21);
map.put('w',22);
map.put('x',23);
map.put('y',24);
map.put('z',25);
int max = Integer.MIN_VALUE;//最大的次数
char maxc = ' ';
int maxID = 0;
for(int i = 0; i < s.length(); i++){
count[map.get(s.charAt(i))]++;
int temp = count[map.get(s.charAt(i))];
if(temp > max || temp == max && map.get(s.charAt(i)) < maxID){
max = temp;
maxc = s.charAt(i);
maxID = map.get(s.charAt(i));
}
}
System.out.println(maxc);
System.out.println(max);
}
}
AC结果
思路
题目要求输入一串字符,然后统计哪一个字母出现次数最多,返回这个字母和它的出现次数。利用一个大小为26的int数组进行统计,用哈希表存储各个字母对应的序号,然后遍历字符串。每读到一个字母时,就在数组中对应的位置的值自增。在此过程中,用max记录最大出现次数,maxc记录出现次数最多的字母,maxID记录当前出现次数最多的字母对应的序号。(题目要求,当出现多个字母出现次数一样多的情况,返回字母序号小的,因此需要记录字母的对应序号)
一、获取数据
Scanner input = new Scanner(System.in);
String s = input.nextLine();
int[] count = new int[26];
获取输入的字符串。同时,先声明用于记录26个字母出现次数的int数组。
二、建立哈希表
Map<Character,Integer> map = new HashMap<>();
map.put('a',0);
map.put('b',1);
map.put('c',2);
map.put('d',3);
map.put('e',4);
map.put('f',5);
map.put('g',6);
map.put('h',7);
map.put('i',8);
map.put('j',9);
map.put('k',10);
map.put('l',11);
map.put('m',12);
map.put('n',13);
map.put('o',14);
map.put('p',15);
map.put('q',16);
map.put('r',17);
map.put('s',18);
map.put('t',19);
map.put('u',20);
map.put('v',21);
map.put('w',22);
map.put('x',23);
map.put('y',24);
map.put('z',25);
这个哈希表的作用是,让26个字母与序号0-25分别对应起来,以便于遍历字符串识别字母的时候可以在数组count中找到对应正确的位置。
三、计数
int max = Integer.MIN_VALUE;//最大的次数
char maxc = ' ';
int maxID = 0;
for(int i = 0; i < s.length(); i++){
count[map.get(s.charAt(i))]++;
int temp = count[map.get(s.charAt(i))];
if(temp > max || temp == max && map.get(s.charAt(i)) < maxID){
max = temp;
maxc = s.charAt(i);
maxID = map.get(s.charAt(i));
}
}
System.out.println(maxc);
System.out.println(max);
max记录出现的最多次数,maxc记录出现最多次数的字母,maxID记录出现最多次数字母的序号。遍历字符串,读到每一个字母然后根据哈希表找到该字母在count数组对应的位置,然后该值+1。并用max、maxc、maxID记录下来。最后输出打印maxc和max就可以了。