本帖最后由 騛鹏 于 2013-4-7 02:00 编辑
- import java.util.*;
- class MapTest4
- {
- public static void main(String[] args)
- {
- String s = "welcome to chinaworld";
- char[] chs = s.toCharArray();
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
- int count = 0;
- for(int x=0; x<chs.length; x++)
- {
- if(chs[x]==' ')
- continue;
- Integer value = tm.get(chs[x]);
-
- if(value!=null)
- count = value;
- count++;
- tm.put(chs[x],count);
- count = 0;
- }
- StringBuilder sb = new StringBuilder();
-
- Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
- Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
- while (it.hasNext())
- {
- Map.Entry<Character,Integer> me = it.next();
- Character ch = me.getKey();
- Integer value = me.getValue();
- sb.append(ch+"="+value+'\n');
- }
- System.out.println(sb.toString());
- }
- }
复制代码 代码较繁琐,唯一的优点是排了序。
从上面的回答看,藤椅的方法 :时间复杂度 n(字符串长度) ,灵活性强(不区分大小写及标点符)
板凳的方法: n 弱
报纸的方法: n*(n+1)/2 强 |