字符串个数统计问题
如STRING s ="abcabcaaaa1234"
则出现字符最多次数的是a怎么用程序实现呢

解决方案 »

  1.   


    String s ="abcabcaaaa1234";
    Map map = new HashMap();
    for (int i = 0; i < s.length(); i++) {
      Character c = Character.valueOf(s[i]);
      Integer n = (Integer)map.get(c);
      if (n == null) {
        n = Integer.valueOf(0);
        map.put(c, n);
      }
    }
    int max = -1;
    char ch = '\0';
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()); {
      Map.Entry e = it.next();
      Character c = (Character)e.getKey();
      Integer n = (Integer)e.getValue();
      if (n.intValue() > max) {
        max = n;
        ch = c.charValue;
      }
    }
    if (max < 0) {
      System.out.println("-- empty input.");
    } else {
      System.out.println("character " + String.valueOf(c) + " appears " + max + " time(s)");
    }粗略写一下,大意如此,没调试。
      

  2.   

    以此为准:
    String s ="abcabcaaaa1234";
    Map map = new HashMap();
    for (int i = 0; i < s.length(); i++) {
      Character c = Character.valueOf(s[i]);
      Integer n = (Integer)map.get(c);
      if (n == null) {
        n = Integer.valueOf(0);
      }
      n = Integer.valueOf(1 + n.intValue());
      map.put(c, n);
    }
    int max = -1;
    char ch = '\0';
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()); {
      Map.Entry e = it.next();
      Character c = (Character)e.getKey();
      Integer n = (Integer)e.getValue();
      if (n.intValue() > max) {
        max = n;
        ch = c.charValue();
      }
    }
    if (max < 0) {
      System.out.println("-- empty input.");
    } else {
      System.out.println("character " + String.valueOf(c) + " appears " + max + " time(s)");
    }
      

  3.   


            /*  得到字符串的首字符,删除字符串中所有的该字符,得到字符个数。
     *  依次循环至字符串为空串结束。
     *  程序能够统计字符最大个数相同得情况。比如aaabbb;
    */
    public static void getMostCh(String str){
    List<Character> cList=new ArrayList<Character>();
    int count=0;
    int max=-1;
    while(!str.equals("")){
    char c=str.charAt(0);
    String temp=str;
    str=str.replaceAll(""+c,"");
    count=temp.length()-str.length();
    if(count>max){
    max=count;
    cList.clear();
    cList.add(c);
    }else if(count== max){
    cList.add(c);
    }
    }

    for (Iterator iter = cList.iterator(); iter.hasNext();) {
    Character element = (Character) iter.next();
    System.out.println(element);
    }

    }
      

  4.   

    两种方式都实现的很巧, 
    在10000个字符串中测试, 两者速度都差不多, 
    jayflee稍微快了几MS