给定一个string数组article及其大小n及一个待统计单词word,请返回该单词在数组中出现的频数。文章的词数在1000以内。
import java.util.*; public class Frequency { public int getFrequency(String[] article, int n, String word) { // write code here HashMap<String, Integer> count = new HashMap<> (); for (int i = 0; i < n; i++) { String k = article[i]; if (count.containsKey(k)) { count.replace(k, count.get(k) + 1); }else { count.put(k, 1); } } if (count.containsKey(word)) { return count.get(word); }else { return 0; } } }
import java.util.*; public class Frequency { public int getFrequency(String[] article, int n, String word) { TrieNode root = new TrieNode(); for (int i = 0; i < n; i ++) { root.insert(article[i]); } TrieNode p = root.search(word); if (p == null) { return 0; } else { return p.cnt; } } public static class TrieNode { public TrieNode[] son; public int cnt; public TrieNode() { this.son = new TrieNode[26]; this.cnt = 0; } public void insert(String word) { if (word == null || word.length() == 0) { return; } TrieNode p = this; for (int i = 0, len = word.length(); i < len; i++) { int loc = word.charAt(i) - 'a'; if (p.son[loc] == null) { p.son[loc] = new TrieNode(); } p = p.son[loc]; } p.cnt++; } public TrieNode search(String word) { if (word == null || word.length() == 0) { return null; } TrieNode p = this; for (int i = 0, len = word.length(); i < len; i++) { int loc = word.charAt(i) - 'a'; if (p.son[loc] == null) { return null; } p = p.son[loc]; } return p; } } }