`

treeMap统计字符

 
阅读更多
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class countStr {
    public static void main(String[] args) {
        String str = "eabcdssasbccdddddsesssaaa";
        countStr(str);
    }
    public static void countStr(String str){
        String tempStr = null;
        Map<String, Integer> map = new TreeMap<String, Integer>();
       
        //利用Map的“key是不能重复的,如果重复则覆盖之前的内容”的特点,只需遍历一次即可完成
        for(int i=0;i<str.length();i++){
            tempStr = str.substring(i, i+1);
            map.put(tempStr, getMapNull(map.get(tempStr))+1);
        }
       
        int max = Collections.max(map.values()); 
        int min = Collections.min(map.values()); 
        System.out.println("字符串中出现最多的次数是:"+max+"次");
        System.out.println("字符串中出现最少的次数是:"+min+"次");
    }
   
    //当map中还没有存入某个字符x时,让map.get("x")返回零值
    public static Integer getMapNull(Object o){
        if(o==null)
            return new Integer(0);
        return (Integer) o;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics