标签:详细 int false example may NPU baidu bsp 应该
Implement a trie with insert
, search
, and startsWith
methods.
Example:
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true
Note:
a-z
.class Trie { private int SIZE = 26; private TrieNode root; /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); } private class TrieNode{ private int num; private TrieNode[] son; private boolean isEnd; private char val; private boolean haveSon; TrieNode(){ num = 1; son = new TrieNode[SIZE]; isEnd = false; haveSon = false; } } /** Inserts a word into the trie. */ public void insert(String word) { if(word.length() == 0 || word == null) return; TrieNode node = root; char[] letters = word.toCharArray(); for(int i = 0; i < word.length(); i++){ int pos = letters[i] - ‘a‘; if(node.son[pos] == null){ node.son[pos] = new TrieNode(); node.son[pos].val = letters[i]; } else node.son[pos].num++; node = node.son[pos]; } node.isEnd = true; } /** Returns if the word is in the trie. */ public boolean search(String word) { if(word.length() == 0 || word == null) return false; TrieNode node = root; char[] letters = word.toCharArray(); for(int i = 0; i < word.length();i++){ int pos = letters[i] - ‘a‘; if(node.son[pos] == null) return false; else node = node.son[pos]; } return node.isEnd; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { if(prefix == null || prefix.length() == 0) return false; TrieNode node = root; char[] letters = prefix.toCharArray(); for(int i = 0; i < prefix.length(); i++){ int pos = letters[i] - ‘a‘; if(node.son[pos] == null) return false; else node = node.son[pos]; } return true; } }
很有意义的题目,prefix tree,root不包含任何val。
https://baike.baidu.com/item/%E5%AD%97%E5%85%B8%E6%A0%91/9825209?fr=aladdin
详细讲解在这里。
一个trie里面应该要有TrieNode,TrieNode里面有son[], num, val, haveSon, isEnd,其中son是儿子数组,num是由根经过此点的单词数量,isEnd是是否到底了。
然后是各种method,无论是insert还是search都要从root开始,所以初始化都要先把root提出来,insert如果当前char不存在,就新建一个trieNode。如果存在就num++。
search更简单,从头到尾找有没有对应的TrieNode,最后返回是不是到底了。找prefix是search的简单版,如果中间没有任何差错,遍历完就可以返回true。
208. Implement Trie (Prefix Tree)
标签:详细 int false example may NPU baidu bsp 应该
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12892496.html