思路:
把单词里每个字母的出现次数存入数组,比较大小后输出。(也可排序后取出索引)
源代码:
import java.util.*;
public class G{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
String word = s.next(); //输入字符串
int count[] = new int[27];//count[0]代表a,count[1]代表b……
int max = 0; //最多出现次数
Character c = null; //存储出现次数最多的字母
for(int i = 0;i < word.length();i++){//依次提取字符串每个字符,出现一次就在count数组对应位置+1
count[word.charAt(i)-97]++; //a=count[0],b=count[1]……
}
for(int i = 0;i< 26;i++)//比较每个count和max的大小
if(count[i]>max){ //count大于max则max=count
max = count[i];
c = (char)(i+97); //97为a的ASCII值,i+97为count对应字母
}else if(count[i]==max){ //若count对于字母出现次数与max相等
if(word.charAt(i)<i+97){ //则比较字典序
c = (char)(i+97);
}
}
}
System.out.println(c);
System.out.println(max);
}
}