package org.pie.audition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Test01_统计字母出现次数 {
/**
* 1.取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq",输出格式为:a(2)b(1)k(2)...
*/
public static void main(String[] args) {
String str = new Scanner(System.in).nextLine();
char[] ch = str.toCharArray();
HashMap<Character, Integer> hs =new HashMap<>();
ArrayList<Character> al = new ArrayList<>();
for (int i = 0; i < ch.length; i++) {
if(! hs.containsKey(ch[i])) {
hs.put(ch[i], 1);
al.add(ch[i]);
}else {
hs.put(ch[i], hs.get(ch[i]) + 1);
}
}
for (Character c : hs.keySet()) {
System.out.print(c + "(" + hs.get(c) + ")");
}
/* char[] ch = new char[26];
int[] arr = new int[26];
for (int i = 0; i < ch.length; i++) { //初始化1-26,a-z
ch[i] = (char)('a'+i);
arr[i] = 0;
}
for (int i = 0; i < ch.length; i++) { //万能的替换法,可以不用arr数组
String str0 = str.replace(""+ ch[i],"");
if(str0.length()!=str.length()) {
System.out.print(ch[i]+"("+(str.length()-str0.length())+")");
}
}*/
/* for (int i = 0; i < str.length(); i++) { //分析每个字符(传统)
for (int j = 0; j < ch.length; j++) {
if(str.charAt(i) == ch[j]) {
arr[j]++;
break;
}
}
}
for (int i = 0; i < arr.length; i++) {
if(arr[i] != 0) {
System.out.print(ch[i] + "(" + arr[i] + ")");
}
}*/
}
}
|