java计算给定字符串中出现次数最多的字母和该字母出现次数的方法

作者:简简单单 2017-03-13
 代码如下复制代码

importJava.util.Collections;

importjava.util.Map;

importjava.util.TreeMap;

publicclassTestStringSplict {

  publicstaticvoidmain(String[] args){

    String str ="aaaaaaaccccccccccccccccccccccaaaabb";

//   用map实现

//   TreeMapmap = new TreeMap();

//   for(Character ch : str.toCharArray()){

//     if((ch>='a' && ch<'z')||(ch>'A' && ch<'Z')){

//       Integer count = map.get(ch);

//       map.put(ch, null==count?1:count+1);

//     }

//   }

//

//   System.out.println(Collections.max(map.values()));

    //用普通数组实现

    int[] aa =newint[60];

    for(chartemp:str.toCharArray()){

      if((temp>=65&& temp<=90)||(temp>=97&& temp<=122)){

        temp -=65;

        aa[temp]++;

      }

    }

    intmax = aa[0];intposition =0;

    for(inti=0;i

      if(aa[i]>max){

        max = aa[i]; position = i;

      }

    }

    System.out.println(max);

        System.out.println("字母"+(char)(position+65) +"出现"+ max +"次");

  }

}

相关文章

精彩推荐