# Leetcode 208. Implement Trie (Prefix Tree) ###### tags: `Leetcode(JAVA)` 題目 : https://leetcode.com/problems/implement-trie-prefix-tree/ 。 想法 : TRIE練習題。 時間複雜度 : O(n * l)。 程式碼 : (JAVA) ``` class Trie { class Node{ Node[] child; boolean isEnd; Node(){ child = new Node[26]; } } Node root; public Trie() { root = new Node(); } public void insert(String word) { Node curr = root; for(int i = 0 ; i < word.length() ; i++){ char ch = word.charAt(i); if(curr.child[ch - 'a'] == null){ curr.child[ch - 'a'] = new Node(); } curr = curr.child[ch-'a']; } curr.isEnd = true; } public boolean search(String word) { Node curr = root; for(int i = 0 ; i < word.length() ; i++){ char ch = word.charAt(i); if(curr.child[ch - 'a'] == null){ return false; } curr = curr.child[ch - 'a']; } return curr.isEnd; } public boolean startsWith(String prefix) { Node curr = root; for(int i = 0 ; i < prefix.length() ; i++){ char ch = prefix.charAt(i); if(curr.child[ch - 'a'] == null){ return false; } curr = curr.child[ch - 'a']; } return true; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */ ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up