295,实现 Trie (前缀树)
作者:互联网
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 true trie.search("app"); // 返回 false trie.startsWith("app"); // 返回 true trie.insert("app"); trie.search("app"); // 返回 true
说明:
-
你可以假设所有的输入都是由小写字母 a-z 构成的。
-
保证所有输入均为非空字符串。
答案:
1class TrieNode {
2 boolean isEnd;
3 TrieNode[] children;
4
5 public TrieNode() {
6 isEnd = true;
7 children = new TrieNode[26];
8 }
9}
10
11public class Trie {
12 private TrieNode root;
13
14 public Trie() {
15 root = new TrieNode();
16 }
17
18 public void insert(String word) {
19 TrieNode current = root;
20 for (int i = 0, L = word.length(); i < L; i++) {
21 int id = word.charAt(i) - 'a';
22 if (current.children[id] == null) {
23 current.children[id] = new TrieNode();
24 current.children[id].isEnd = false;
25 }
26 current = current.children[id];
27 }
28 current.isEnd = true;
29 }
30
31 public boolean search(String word) {
32 return search(word, 1);
33 }
34
35 public boolean startsWith(String prefix) {
36 return search(prefix, 2);
37 }
38
39 private boolean search(String str, int type) {
40 TrieNode current = root;
41 int i = -1, L = str.length();
42 while (++i < L) {
43 int id = str.charAt(i) - 'a';
44 if ((current = current.children[id]) == null) return false;
45 }
46 return type == 1 ? current.isEnd : true;
47 }
48}
解析:
如果对哈夫曼树比较熟悉的话,这题很容易理解,这题没什么难度,我们再来看另一种解法
1class TrieNode {
2 public char val;
3 public boolean isWord;
4 public TrieNode[] children = new TrieNode[26];
5
6 public TrieNode() {
7 }
8
9 TrieNode(char c) {
10 TrieNode node = new TrieNode();
11 node.val = c;
12 }
13}
14
15public class Trie {
16 private TrieNode root;
17
18 public Trie() {
19 root = new TrieNode();
20 root.val = ' ';
21 }
22
23 public void insert(String word) {
24 TrieNode ws = root;
25 for (int i = 0; i < word.length(); i++) {
26 char c = word.charAt(i);
27 if (ws.children[c - 'a'] == null) {
28 ws.children[c - 'a'] = new TrieNode(c);
29 }
30 ws = ws.children[c - 'a'];
31 }
32 ws.isWord = true;
33 }
34
35 public boolean search(String word) {
36 TrieNode ws = root;
37 for (int i = 0; i < word.length(); i++) {
38 char c = word.charAt(i);
39 if (ws.children[c - 'a'] == null)
40 return false;
41 ws = ws.children[c - 'a'];
42 }
43 return ws.isWord;
44 }
45
46 public boolean startsWith(String prefix) {
47 TrieNode ws = root;
48 for (int i = 0; i < prefix.length(); i++) {
49 char c = prefix.charAt(i);
50 if (ws.children[c - 'a'] == null)
51 return false;
52 ws = ws.children[c - 'a'];
53 }
54 return true;
55 }
56}
标签:前缀,Trie,public,current,TrieNode,ws,295,root,children 来源: https://blog.51cto.com/u_4774266/2902565