一个字符串中可能包含
a
~
z
中的多个字符,如有重复,求出现次数最多的那个字母及次数,如有多个重复则都求出来。
- import java.util.*;
- import java.util.Collections;
- public class LetterCount
- {
- public void getLetterCount(String str)
- {
- ArrayList<String> lists = new ArrayList<String>();
- HashSet<String> hset = new HashSet<String>();
- char[] ss = str.toCharArray();
- for(int i=0; i<ss.length; i++)
- {
- lists.add(String.valueOf(ss[i]));
- hset.add(String.valueOf(ss[i]));
- }
- System.out.println("共有字母"+hset.size()+"个!");
- Collections.sort(lists);
- Iterator it = hset.iterator();
- while(it.hasNext())
- {
- String os = (String)it.next();
- int begin = lists.indexOf(os);
- int last = lists.lastIndexOf(os);
- int count = last-begin+1;
- System.out.println("字母"+os+": 共"+count+"个");
- }
- }
- public static void main(String[] args)
- {
- LetterCount lc = new LetterCount();
- lc.getLetterCount(args[0]);
- }
-
}
我的运行结果:
D:/backup/myclass>java LetterCount yekmaakkccekymbvb
共有字母8个!
字母k: 共4个
字母m: 共2个
字母a: 共2个
字母c: 共2个
字母y: 共2个
字母b: 共2个
字母v: 共1个
字母e: 共2个