题目链接:https://leetcode.com/problems/implement-trie-prefix-tree/ 题目:
Implement a trie with insert
, search
, and startsWith
methods.
Note: You may assume that all inputs are consist of lowercase letters a-z
.
思路:
每个结点包括三个属性:结点代表的字符、指向儿子结点的指针、代表该结点是否是word。最后一个属性是因为word不一定是从根到叶结点的路径。比如insert("abc")、insert("ab"),search("ab")应该返回true。因为之前插入了ab,哪怕b不是叶结点,所以结点要有一个属性表示从root到该是否为word。
算法 :
import java.util.HashMap; class TrieNode { String val = "" ; HashMap<String, TrieNode> nexts = new HashMap<String, TrieNode>(); boolean isword = false ; public TrieNode() { } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode p = root; for ( int i = 0 ; i < word.length(); i++) { String key = word.charAt(i) + "" ; if (p.nexts.containsKey(key)) { p = p.nexts.get(key); } else { TrieNode t = new TrieNode(); t.val = key; p.nexts.put(key, t); p = t; } if (i==word.length()- 1 ){ p.isword = true ; } } System.out.println(p.val+":" +p.isword); } public boolean search(String word) { TrieNode p = root; for ( int i = 0 ; i < word.length(); i++) { String key = word.charAt(i) + "" ; if (p.nexts.containsKey(key)) { p = p.nexts.get(key); } else { return false ; } } if (p.nexts.size() == 0 ) return true ; else if (!p.isword) return false ; else return true ; } public boolean startsWith(String prefix) { TrieNode p = root; for ( int i = 0 ; i < prefix.length(); i++) { String key = prefix.charAt(i) + "" ; if (p.nexts.containsKey(key)) { p = p.nexts.get(key); } else { return false ; } } return true ; } }