题目
给定一个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);
}
}

1672

被折叠的 条评论
为什么被折叠?



