public static void main(String[] args) {
/**
* 我做的,利用map来保存,当字符串大的时候我的效率高
*/
String test = "asdqwasdasdasdi";
//统计执行时间
long time1 = System.currentTimeMillis();
char[] data = test.toCharArray();
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=0;i<data.length;i++)
{
char[] temp = {data[i]};
String key = new String(temp);
//先检查该字符是否存在map中,存在value值加1,不存在存入该字符,设置出现次数为1
if(null == map.get(key))
{
map.put(key, 1);
}else{
int value = Integer.valueOf(map.get(key));
map.remove(key);
map.put(key, Integer.valueOf(value+1));
}
}
//输出map的KEY和VALUE
int max = 0; //统计出现次数最多的值的次数
String maxKey = ""; //统计出现次数最多的值
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext())
{
String key = (String)it.next();
// System.out.println("key "+key+" value "+map.get(key));
if(max < Integer.valueOf(map.get(key))){
max = Integer.valueOf(map.get(key));
maxKey = key;
}
}
System.out.println("------------------");
System.out.println("出现次数最多的字符是"+maxKey+",出现次数为"+max+"次");
long time2 = System.currentTimeMillis();
/**
* 别人做的,代码简洁,但是效率低
*/
String str= test;
int len=str.length();
char[] tmp=str.toCharArray();
int maxcount=0;
char maxchar=0;
int tempcount;
for(int i=0;i<len;i++){
tempcount=0;
for(int j=0;j<len;j++){
if(tmp[j]==tmp[i]) tempcount++;
}
//isLetter 确定指定字符是否为字母。
if(tempcount>maxcount&&Character.isLetter(tmp[i])){
maxcount=tempcount;
maxchar=tmp[i];
}
}
System.out.println(maxchar);
System.out.println(maxcount);
long time3 = System.currentTimeMillis();
System.out.println();
System.out.println("第一种方法消耗时间为 "+(time2-time1));
System.out.println("第二种方法消耗时间为 "+(time3-time2));
}