求一个字符串中出现频率最高的字符

这段时间在准备Android面试,Android面试的笔试题中可能会涉及到许多Java知识,包括Java编程。
这里有一道遇见频率比较高的Java编程题:
题目:求一个字符串中出现频率最高的字符
先讲解一下下面这个方法的思路:
- 首先遍历这个字符串,把这个字符串的所有字符保存到一个Set集合中,目的是去除重复的字符,得到这个字符串中有哪些字符。
- 然后遍历Set集合,计算每个字符在字符串中出现的次数,计算的方法就是使用indexOf()方法,逐次索引,如下所示:

 while ((index = tempStr.indexOf(chara)) != -1) {
                count += 1;
                tempStr = tempStr.substring(index + 1);
            }

将每个字符及其出现的次数保存到Map集合中,同时计算出现最多次数的字符出现多少次maxCount。
-再遍历Set集合,根据maxCount得到出现次数最多的是哪些字符。

完整代码如下:

    // 方法二
    public static List<Character> getHighestFrequencyWord(String str) {
        List<Character> charList = new ArrayList<Character>();
        Set<Character> set = new HashSet<Character>();
        for (int i = 0; i < str.length(); i++) {
            set.add(str.charAt(i));
        }
        String tempStr = str;
        Iterator<Character> it = set.iterator();
        int maxCount = -1;
        Character maxCharacter = null;

        Map<Character, Integer> map = new HashMap<Character, Integer>();
        while (it.hasNext()) {
            // System.out.println("--->" + it.next());
            Character chara = it.next();
            int count = 0;
            int index = -1;
            while ((index = tempStr.indexOf(chara)) != -1) {
                count += 1;
                tempStr = tempStr.substring(index + 1);
            }
            map.put(chara, count);
            if (count > maxCount) {
                maxCharacter = chara;
                maxCount = count;
            }
            tempStr = str;
            count = 0;
        }
        it = set.iterator();
        while (it.hasNext()) {
            Character chara = it.next();
            if (map.get(chara) == maxCount) {
                charList.add(chara);
            }
        }
        return charList;
    }
public static void main(String args[]){
 System.out.println("--->" +    getHighestFrequencyWord("aacccfffeess"));
}

运行结果:

--->[c, f]
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值