算法-词频统计

题目

给定一个string数组article及其大小n及一个待统计单词word,请返回该单词在数组中出现的频数。文章的词数在1000以内

解题思路

(1)暴力法
用一个int变量count统计单词word出现的次数,遍历所有的article元素,与word一一比较,如果相等则count+1
代码实现

package com.company.algorithm;
public class WordFrequency {
    public static void main(String[] args) {
        String[] strings = new String[]{"h", "e", "l", "l", "o", "w", "o", "r", "d"};
        System.out.println(wordFrequencyStatistics1(strings, 9, "l"));
    }

    //暴力法:直接遍历整个数组,挨个元素与待比较字符串作比较
    private static int wordFrequencyStatistics1(String[] article, int n, String word) {
        int count = 0;
        for (String s : article) {
            if (s.equals(word)) count++;
        }
        return count;
    }

(2)在数组中元素长度与待比较字符串长度相等的情况下再做是否相等的判断
代码实现

package com.company.algorithm;
public class WordFrequency {
    public static void main(String[] args) {
        String[] strings = new String[]{"h", "e", "l", "l", "o", "w", "o", "r", "d"};
        System.out.println(wordFrequencyStatistics2(strings, 9, "l"));
    }

    private static int wordFrequencyStatistics2(String[] article, int n, String word) {
        int count = 0;
        for (String s : article) {
            if (s != null && s.length() == word.length()) {
                if (s.equals(word)) count++;
            }
        }
        return count;
    }

(3)HashMap以键值对的形式保存数组中所有元素及其出现的次数,最后将待统计单词作为Map的键,获取对应的数值
代码实现

package com.company.algorithm;
import java.util.HashMap;
import java.util.Map;

public class WordFrequency {
    public static void main(String[] args) {
        String[] strings = new String[]{"h", "e", "l", "l", "o", "w", "o", "r", "d"};
        System.out.println(wordFrequencyStatistics3(strings, 9, "l"));
    }
    
    private static int wordFrequencyStatistics3(String[] article, int n, String word) {
        Map<String, Integer> map = new HashMap<>();
        for (String s : article) {
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }
        return map.get(word) == null ? 0 : map.get(word);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值