【題目】給你一個字串,包含了空格等標點符號,要你計算出出現次數最多的字母和該字母出現的次數。
【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);