取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)..

鄙人从网上查询如题问题,发现有两种不同的方法,考虑到效率问题,作如下比较:
1、第一种方法是:直接使用for循环遍历并查找相同的字符,然后次数递增;
2、第二种方法是:用Map存储字符及其出现次数,利用Map种键不能重复这一特点实现;

public class GetCharCount {
    public static void main(String[] args) {
        String string = "abcde%^kka27qoq";
        System.out.println(string);
        long start = System.nanoTime();
        fun1(string);
        long end = System.nanoTime();
        System.out.println("\ncost time:" + (end - start));
        start = System.nanoTime();
        fun2(string);
        end = System.nanoTime();
        System.out.println("\ncost time:" + (end - start));
    }
    public static void fun1(String str) {
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (cs[i] == ' ') {
                continue;
            }
            int count = 1;
            for (int j = i + 1; j < cs.length; j++) {
                if (cs[i] == cs[j]) {
                    count++;
                    cs[j] = ' ';
                }
            }
            System.out.print(cs[i] + "(" + count + ")");
        }
    }

    public static void fun2(String str) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            Integer count = map.get(cs[i]);
            if (count == null) {
                count = 0;
            }
            map.put(cs[i], count + 1);
        }
        Set<Entry<Character, Integer>> entrySet = map.entrySet();
        for (Entry<Character, Integer> entry : entrySet) {
            System.out.print(entry.getKey() + "(" + entry.getValue() + ")");
        }
    }
}

测试截图如下:
测试截图
从上可以发现:用for循环遍历比用Map集合快至少10倍以上;

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值