leetcode 208. Implement Trie (Prefix Tree) | 208. 实现 Trie 前缀树(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 208. Implement Trie (Prefix Tree) | 208. 实现 Trie 前缀树(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/implement-trie-prefix-tree/
題解
第一版:暴力法
import java.util.LinkedHashSet;class Trie {LinkedHashSet<String> set;/** Initialize your data structure here. */public Trie() {set = new LinkedHashSet<>();}/** Inserts a word into the trie. */public void insert(String word) {set.add(word);}/** Returns if the word is in the trie. */public boolean search(String word) {return set.contains(word);}/** Returns if there is any word in the trie that starts with the given prefix. */public boolean startsWith(String prefix) {for (String s : set)if (s.startsWith(prefix)) return true;return false;} }/*** 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);*/第二版:前綴樹的實現
參考:官方題解
Trie node structure
Insertion of a key to a trie
Search for a key in a trie
Search for a key prefix in a trie
My Code
class Node{Node[] map;boolean isEnd;public Node() {this.map = new Node['z' - 'a' + 1];}public Node get(char c) {return map[c - 'a'];}public Node put(char c) {Node node = new Node();map[c - 'a'] = node;return node;} } class Trie {Node node;/** Initialize your data structure here. */public Trie() {node=new Node();}/** Inserts a word into the trie. */public void insert(String word) {char[] chars = word.toCharArray();Node cur = node;for (int i = 0; i < chars.length; i++) {if (cur.get(chars[i]) != null)cur = cur.get(chars[i]);elsecur = cur.put(chars[i]);if (i == chars.length - 1)cur.isEnd = true;}}/** Returns if the word is in the trie. */public boolean search(String word) {Node node = searchPrefix(word);return node != null && node.isEnd;}/** Returns if there is any word in the trie that starts with the given prefix. */public boolean startsWith(String prefix) {Node node = searchPrefix(prefix);return node != null;}public Node searchPrefix(String prefix) {char[] chars = prefix.toCharArray();Node cur = node;for (char c : chars) {if (cur.get(c) == null) return null;// cur.isEnd可能是偽結束符,不能用來判斷是否真正結束遍歷else cur = cur.get(c);}return cur;} }/*** 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);*/附:左神算法 - 子數組最大異或和
總結
以上是生活随笔為你收集整理的leetcode 208. Implement Trie (Prefix Tree) | 208. 实现 Trie 前缀树(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 207. Course
- 下一篇: leetcode 209. Minimu