首页 > 技术文章 > 面试题,计算String中每个字符出现的次数(第二个版本)

yonim 2020-06-14 20:18 原文

上一次我们用的是一个公共查询方法传入字符截取之后的数组查询次数,这样消耗性能,

这一次我们通过定义一个实体类存放值和记录次数,代码如下、

    // ================================================ 分拣思路
    // =========================================================
    

    public static void SortingArray() {
        StringBuilder str = strBuilder();
        String name = str.toString();
        System.out.println("随机出来的字符串是:" + name);
        Map<String,ArrayMap> map = new HashMap<>();
        // 赛选字符容器, 便于后期遍历
        Set<String> set = new HashSet<String>();
        for (int i = 0; i < name.length(); i++) {
            String indexStr = name.substring(i,i+1);
//            System.err.println(indexStr);
            if(null!=map.get(indexStr)) {  // 插入之前先进行判断
                map.get(indexStr).setValue(indexStr);
            }else {
                map.put(indexStr, new ArrayMap(indexStr));
                set.add(indexStr);// 加入容器
            }
        }
        for (String string : set) {  // 遍历
            System.err.println(map.get(string).toString());
        }
    }
}
class ArrayMap {
    private String key;
    private Integer count;
    private String value;
    public void setValue(String value) {
        if(this.value.equals(value)) {
            this.count++;
        }else {
            this.value = value;
            this.key = value;
        }
    }
    public ArrayMap() {
    }
    public ArrayMap(String key) {
        this.key = key;
        this.value=key;
        this.count=1;
    }
    @Override
    public String toString() {
        return this.key+"出现的次数是:"+this.count;
    }
    
}

 

推荐阅读