【题目】给你一个字符串,包含了空格等标点符号,要你计算出出现次数最多的字母和该字母出现的次数。
【code】:
private static void totalTimes(String str) {
char[] ch = str.toCharArray();
Map<Character, Integer> timesMap = new HashMap<Character, Integer>();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 65 && ch[i] <= 90) || (ch[i] >= 97 && ch[i] <= 122)) {
Integer freq = timesMap.get(ch[i]);
timesMap.put(ch[i], freq == null ? Integer.valueOf(1) : ++freq);
}
}
int charMaxIndex = Collections.max(timesMap.values());
int charMinIndex = Collections.min(timesMap.values());
Set<Character> maxSet = new HashSet<Character>();
Set<Character> minSet = new HashSet<Character>();
for(Map.Entry<Character, Integer> entry : timesMap.entrySet()){
if(entry.getValue().equals(charMaxIndex)){
maxSet.add(entry.getKey());
}
if(entry.getValue().equals(charMinIndex)){
minSet.add(entry.getKey());
}
}
System.out.println("出现最多的字母:" + maxSet);
System.out.println("出现次数:" + charMaxIndex);
System.out.println("出现最小的字母:" + minSet);
System.out.println("出现次数:" + charMinIndex);
}
当然,除了以上,每个人都会有自己心中的code,呵呵!如果不能利用到Java里的集合,那么就可能在数组上做文章了,如下:
- String str = "hello wolrd wlllkdsfhksadfls?sdfls sdf.pqyutgvAAAxzsdfs " +
- "lsdfj,ljsfd ajfdsak sfksjdfisfsdkfj lsdfjsidf jsafdalsjfs sfskdfjs" ;
- int [] strCounts = new int [ 255 ];
- int biggestCount = 0 ;
- char biggestCh = 0 ;
- char ch = 0 ;
- int currentCount = 0 ;
- for ( int i = str.length() - 1 ; i >= 0 ; i--) {
- ch = str.charAt(i);
- currentCount = ++strCounts[ch];
- if (currentCount > biggestCount) {
- biggestCount = currentCount;
- biggestCh = ch;
- }
- }
- System.out.println(biggestCh);
- System.out.println(biggestCount);