leetcode 208. 實現 Trie (前綴樹)

Trie(發音類似 “try”)或者說 前綴樹 是一種樹形數據結構,用于高效地存儲和檢索字符串數據集中的鍵。這一數據結構有相當多的應用情景,例如自動補完和拼寫檢查。

請你實現 Trie 類:

Trie() 初始化前綴樹對象。
void insert(String word) 向前綴樹中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前綴樹中,返回 true(即,在檢索之前已經插入);否則,返回 false 。
boolean startsWith(String prefix) 如果之前已經插入的字符串 word 的前綴之一為 prefix ,返回 true ;否則,返回 false 。

示例:

輸入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
輸出
[null, null, true, false, true, null, true]

解釋
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 True
trie.search(“app”); // 返回 False
trie.startsWith(“app”); // 返回 True
trie.insert(“app”);
trie.search(“app”); // 返回 True

解題思路

前綴樹節點由子節點數組以及是否為單詞末尾標記組成,子節點數組由26個子節點構成,當數組某個元素為空時,代表該前綴后面不存在相應的字母。
注意:在插入時需要給單詞末尾打上標記,判斷到達該節點時,是否存在一個完整的單詞
總的來說就是構建一個26叉樹(代表后續的26個字母),從根節點出發,到達isEnd為true的路徑都是一個單詞

代碼

    class Trie {TrieNode root=new TrieNode();/** Initialize your data structure here. */public Trie() {}/** Inserts a word into the trie. */public void insert(String word) {TrieNode cur=root;for (int i = 0; i < word.length(); i++) {cur=cur.insert(word.charAt(i));}cur.setEnd(true);}/** Returns if the word is in the trie. */public boolean search(String word) {TrieNode cur=root;for (int i = 0; i < word.length(); i++) {cur = cur.getChild(word.charAt(i));if(cur==null) return false;}return cur.isEnd;}/** Returns if there is any word in the trie that starts with the given prefix. */public boolean startsWith(String word) {TrieNode cur=root;for (int i = 0; i < word.length(); i++) {cur = cur.getChild(word.charAt(i));if(cur==null) return false;}return true;}}class TrieNode{TrieNode[] next;boolean isEnd=false;public TrieNode() {next=new TrieNode[26];}public boolean isEnd() {return isEnd;}public void setEnd(boolean end) {isEnd = end;}public TrieNode getChild(char c){return next[c-'a'];}public TrieNode insert(char c) {if (getChild(c) == null){next[c-'a']=new TrieNode();}return getChild(c);}}
/*** 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);*/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391419.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391419.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391419.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

那些年收藏的技術文章(一) CSDN篇

#Android ##Android基礎及相關機制 Android Context 上下文 你必須知道的一切 Android中子線程真的不能更新UI嗎&#xff1f; Android基礎和運行機制 Android任務和返回棧完全解析&#xff0c;細數那些你所不知道的細節 【凱子哥帶你學Framework】Activity啟動過程全解析 【凱子…

chrome json插件_如何使用此免費的Chrome擴展程序(或Firefox插件)獲取易于閱讀的JSON樹

chrome json插件JSON is a very popular file format. Sometimes we may have a JSON object inside a browser tab that we need to read and this can be difficult.JSON是一種非常流行的文件格式。 有時我們可能需要在瀏覽器選項卡中包含一個JSON對象&#xff0c;這很困難。…

test10

test10 轉載于:https://www.cnblogs.com/Forever77/p/11447638.html

數據倉庫項目分析_數據分析項目:倉庫庫存

數據倉庫項目分析The code for this project can be found at my GitHub.該項目的代碼可以在我的GitHub上找到 。 介紹 (Introduction) The goal of this project was to analyse historic stock/inventory data to decide how much stock of each item a retailer should hol…

leetcode 213. 打家劫舍 II(dp)

你是一個專業的小偷&#xff0c;計劃偷竊沿街的房屋&#xff0c;每間房內都藏有一定的現金。這個地方所有的房屋都 圍成一圈 &#xff0c;這意味著第一個房屋和最后一個房屋是緊挨著的。同時&#xff0c;相鄰的房屋裝有相互連通的防盜系統&#xff0c;如果兩間相鄰的房屋在同一…

HTTP緩存的深入介紹:Cache-Control和Vary

簡介-本文范圍 (Introduction - scope of the article) This series of articles deals with caching in the context of HTTP. When properly done, caching can increase the performance of your application by an order of magnitude. On the contrary, when overlooked o…

059——VUE中vue-router之路由嵌套在文章系統中的使用方法:

<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>vue-router之路由嵌套在文章系統中的使用方法&#xff1a;</title><script src"vue.js"></script><script src"v…

web前端效率提升之瀏覽器與本地文件的映射-遁地龍卷風

1.chrome瀏覽器&#xff0c;機制是攔截url&#xff0c;      1.在瀏覽器Element中調節的css樣式可以直接同步到本地文件&#xff0c;反之亦然&#xff0c;瀏覽器會重新加載css&#xff0c;省去刷新   2.在source面板下對js的編輯可以同步到本地文件&#xff0c;反之亦然…

linux : 各個發行版中修改python27默認編碼為utf-8

該方法可解決robot報錯&#xff1a;ascii codec cant encode character u\xf1 in position 16: ordinal not in range(128) 在下面目錄中新增文件&#xff1a;sitecustomize.py 內容為 #codingutf-8 import sysreload(sys) sys.setdefaultencoding(utf8) 各個發行版放置位置&a…

歸因分析_歸因分析:如何衡量影響? (第2部分,共2部分)

歸因分析By Lisa Cohen, Ryan Bouchard, Jane Huang, Daniel Yehdego and Siddharth Kumar由 麗莎科恩 &#xff0c; 瑞安布沙爾 &#xff0c; 黃美珍 &#xff0c; 丹尼爾Yehdego 和 亞洲時報Siddharth庫馬爾 介紹 (Introduction) This is our second article in a series wh…

ubuntu恢復系統_Ubuntu恢復菜單:揭開Linux系統恢復神秘面紗

ubuntu恢復系統Don’t try to convince yourself otherwise: along with all the good stuff, you’re going to have bad days with Linux.否則&#xff0c;請不要試圖說服自己&#xff1a;與所有好的東西一起&#xff0c;您將在Linux上度過糟糕的日子。 You (or the users y…

linux與磁盤相關的內容

本節所講內容1.認識SAS-SATA-SSD-SCSI-IDE硬盤2.使用fdisk對磁盤進行操作&#xff0c;分區&#xff0c;格式化3.開機自動掛載分區4.使用parted操作大于等于4T硬盤5.擴展服務器swap內存空間 MBR(Master Boot Record)主引導記錄&#xff0c;也就是現有的硬盤分區模式。MBR分區的標…

leetcode 87. 擾亂字符串(dp)

使用下面描述的算法可以擾亂字符串 s 得到字符串 t &#xff1a; 如果字符串的長度為 1 &#xff0c;算法停止 如果字符串的長度 > 1 &#xff0c;執行下述步驟&#xff1a; 在一個隨機下標處將字符串分割成兩個非空的子字符串。即&#xff0c;如果已知字符串 s &#xff0c…

頁面布局

頁面布局兩大類&#xff1a;   主站&#xff1a; 1 <div classpg-header> 2 <div stylewidth:980px;margin:0 auto;> 3 內容自動居中 4 </div> 5 <div classpg-content></div> 6 <div classpg-footer></div&…

sonar:默認的掃描規則

https://blog.csdn.net/liumiaocn/article/details/83550309 https://note.youdao.com/ynoteshare1/index.html?id3c1e6a08a21ada4dfe0123281637e299&typenote https://blog.csdn.net/liumiaocn/article/details/83550309 文本版&#xff1a; soanr規則java版 …

多變量線性相關分析_如何測量多個變量之間的“非線性相關性”?

多變量線性相關分析現實世界中的數據科學 (Data Science in the Real World) This article aims to present two ways of calculating non linear correlation between any number of discrete variables. The objective for a data analysis project is twofold : on the one …

wp博客寫文章500錯誤_500多個博客文章教我如何撰寫出色的文章

wp博客寫文章500錯誤Ive written a lot of blog posts. Somewhere north of 500 to be exact. All of them are technical. 我寫了很多博客文章。 確切地說是在500以北的某個地方。 所有這些都是技術性的。 About two dozen of them are actually good. 實際上大約有兩打是不錯…

leetcode 220. 存在重復元素 III(排序)

給你一個整數數組 nums 和兩個整數 k 和 t 。請你判斷是否存在 兩個不同下標 i 和 j&#xff0c;使得 abs(nums[i] - nums[j]) < t &#xff0c;同時又滿足 abs(i - j) < k 。 如果存在則返回 true&#xff0c;不存在返回 false。 示例 1&#xff1a; 輸入&#xff1a…

ON DUPLICATE KEY UPDATE

INSERT INTO ON DUPLICATE KEY UPDATE 與 REPLACE INTO&#xff0c;兩個命令可以處理重復鍵值問題&#xff0c;在實際上它之間有什么區別呢&#xff1f;前提條件是這個表必須有一個唯一索引或主鍵。1、REPLACE發現重復的先刪除再插入&#xff0c;如果記錄有多個字段&#xff0c…

os.path 模塊

os.path.abspath(path) #返回絕對路徑os.path.basename(path) #返回文件名os.path.commonprefix(list) #返回list(多個路徑)中&#xff0c;所有path共有的最長的路徑。os.path.dirname(path) #返回文件路徑os.path.exists(path) #路徑存在則返回True,路徑損壞返回Falseos.path…