輸入幾個不重復的單詞和幾個前綴,分別統計出單詞中包含前綴的個數。
這個題目用到了 Trie
樹.它在百度百科中的定義如下:在計算機科學中,Trie,又稱字典樹、單詞查找樹或鍵樹,是一種樹形結構,是一種哈希樹的變種。典型應用是用於統計,排序和保存大量的字符串(但不僅限於字符串),所以經常被搜索引擎系統用於文本詞頻統計。它的優點是:利用字符串的公共前綴來減少查詢時間,最大限度地減少無謂的字符串比較,查詢效率比哈希樹高。Trie的核心思想是空間換時間,利用字符串的公共前綴來降低查詢時間的開銷以達到提高效率的目的。它有3個基本性質:根節點不包含字符,除根節點外每一個節點都只包含一個字符。從根節點到某一節點,路徑上經過的字符連接起來,為該節點對應的字符串。每個節點的所有子節點包含的字符都不相同。
package algorithm.tree;
public class Trie {
class Node {
char value;
byte end = 0;
Node[] next = new Node[26];
int count;
}
private Node root;
public Trie() {
root = new Node();
}
public boolean put(String value) {
if (value == null || value.isEmpty()) {
return false;
}
Node p = root;
int index;
char[] values = value.toCharArray();
for (int i = 0; i < values.length; i++) {
index = values[i] - 'a';
if (p.next[index] == null) {
Node node = new Node();
node.value = values[i];
p.next[index] = node;
}
p = p.next[index];
p.end = 0;
p.count++;
}
p.end = 1;
return true;
}
public boolean find(String value,boolean pattern) {
if (value == null || value.isEmpty()) {
return false;
}
Node p = root;
char[] values = value.toCharArray();
for (int i = 0; i < values.length; i++) {
int index = values[i] - 'a';
if (p.next[index] == null) {
return false;
}
p = p.next[index];
}
return pattern ? true : p.end == 1;
}
public int count(String value) {
if (value == null || value.isEmpty()) {
return 0;
}
Node p = root;
char[] values = value.toCharArray();
for (int i = 0; i < values.length; i++) {
int index = values[i] - 'a';
if (p.next[index] == null) {
return 0;
}
p = p.next[index];
}
return p.count;
}
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.put("banana");
trie.put("band");
trie.put("bee");
trie.put("absolute");
trie.put("acm");
//2
int count1 = trie.count("ba");
//3
int count2 = trie.count("b");
//1
int count3 = trie.count("band");
//0
int count4 = trie.count("abc");
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。