当前位置:网站首页>LeetCode_ Prefix tree_ Medium_ 208. implement trie (prefix tree)
LeetCode_ Prefix tree_ Medium_ 208. implement trie (prefix tree)
2022-06-11 18:08:00 【I've been up and down in the Jianghu】
1. subject
Trie( It sounds like “try”) Or say Prefix tree It's a tree data structure , Keys for efficient storage and retrieval of string datasets . This data structure has quite a number of application scenarios , For example, automatic completion and spelling check .
Please realize Trie class :
Trie() Initialize the prefix tree object .
void insert(String word) Insert a string into the forward tree word .
boolean search(String word) If the string word In the prefix tree , return true( namely , Has been inserted before retrieval ); otherwise , return false .
boolean startsWith(String prefix) If a string has been inserted before word One of the prefixes of is prefix , return true ; otherwise , return false .
Example :
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
explain
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Tips :
1 <= word.length, prefix.length <= 2000
word and prefix It's only made up of lowercase letters
insert、search and startsWith The total number of calls does not exceed 3 * 104 Time
source : Power button (LeetCode)
link :https://leetcode.cn/problems/implement-trie-prefix-tree
2. Ideas
(1) Prefix tree
Train of thought reference Official solution to this problem .
A prefix tree is essentially a multitree derived from a binary tree , But it is different from the previous ordinary multi tree nodes , In its nodes children The index of an array makes sense , It represents a character in the key .
3. Code implementation (Java)
// Ideas 1———— Prefix tree
class Trie {
private Trie[] children;
private boolean isEnd;
public Trie() {
// Each node has at most 26 Child node , They correspond to each other 26 Lowercase letters
children = new Trie[26];
isEnd = false;
}
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
Trie node = searchPrefix(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
public Trie searchPrefix(String prefix) {
Trie node = this;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
return null;
}
node = node.children[index];
}
return node;
}
}
/** * 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); */
边栏推荐
- Understanding of distributed transactions
- Kubernetes deploys elk and collects container logs using filebeat
- Chorus翻译
- Spring 2021 daily question [week7 not finished]
- Line up to pick up the express. At this meeting, I sorted out all kinds of code sets
- R language to find missing value location of data set
- Rtsp/onvif protocol easynvr video platform arm version cross compilation process and common error handling
- 网络安全威胁情报体系
- Say no to credit card fraud! 100 lines of code to realize simplified real-time fraud detection
- 【先收藏,早晚用得到】100个Flink高频面试题系列(二)
猜你喜欢

Initial egg framework

Hello go (XV). Go language common standard library V
![[piecemeal knowledge] [network composition] the mobile phone can be connected to the campus network, but the computer can't](/img/a1/7858a0651ddca0dfd187dc128b2036.jpg)
[piecemeal knowledge] [network composition] the mobile phone can be connected to the campus network, but the computer can't

Tle6389-2g V50's unique pwm/pfm control scheme has a duty cycle of up to 100%, forming a very low differential pressure - keshijin mall

Say no to credit card fraud! 100 lines of code to realize simplified real-time fraud detection

Service learning notes 01 start method and life cycle

mariadb spider分片引擎初体验

【先收藏,早晚用得到】100个Flink高频面试题系列(一)

Tle6288r is a 6-channel (150 MOhm) intelligent multi-channel switch using intelligent power technology - keshijin mall

jsfinder,wafw00f安装,nmap配置(缺少msvcr120.dll文件)
随机推荐
spawn ./ gradlew EACCES at Process. ChildProcess._ handle. onexit
Global and Chinese market of high frequency bipolar junction transistors 2022-2028: Research Report on technology, participants, trends, market size and share
在同花顺上面开股票账户好不好,安不安全?
Codeworks round 481 (Div. 3) [done]
6-2 reverse output of multiple integers recursion
Tidb CDC synchronization of features not available in MySQL to MySQL
TestPattern error
Chorus翻译
Service learning notes 03 front desk service practice
File class learning
System learning typescript (V) - joint type
任意用户密码重置的10种方式
SQL语句当查询条件为空时默认查询全部数据,不为空是则按照条件进行查询
Rtsp/onvif protocol easynvr video platform arm version cross compilation process and common error handling
Explain AI accelerators in detail: GPU, DPU, IPU, TPU... There are infinite possibilities for AI acceleration schemes
Winter vacation daily question (improvement group) [end of week 4]
智能化整体图例,布线、安防、广播会议、电视、楼宇、消防、电气图的图例【转自微信公众号弱电课堂】
简单理解事件
Say no to credit card fraud! 100 lines of code to realize simplified real-time fraud detection
Tidb CDC create task error unknown or incorrect time zone