日期:2014-05-20  浏览次数:20631 次

字符串个数统计问题
字符串个数统计问题
如STRING s ="abcabcaaaa1234"
则出现字符最多次数的是a

怎么用程序实现呢

------解决方案--------------------
Java code

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)");
}

------解决方案--------------------
以此为准:

Java code

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)");
}