//Implement Trie (Prefix Tree)
//Implement a trie with insert, search, and startsWith methods.
//You may assume that all inputs are consist of lowercase letters a-z.
class MYTrieNode {
char val;
boolean isWord;
MYTrieNode[] subNodes = new MYTrieNode[26];
MYTrieNode(char val) {
this.val = val;
}
}
class Trie {
private MYTrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new MYTrieNode(' ');
}
/** Inserts a word into the trie. */
public void insert(String word) {
MYTrieNode node = root;
for (int i = 0; i < word.length(); i++) {
if (node.subNodes[word.charAt(i) - 'a'] != null) {
node = node.subNodes[word.charAt(i) - 'a'] ;
} else {
node.subNodes[word.charAt(i) - 'a'] = new MYTrieNode(word.charAt(i));
node = node.subNodes[word.charAt(i) - 'a'];
}
}
node.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
MYTrieNode node = root;
for (int i = 0; i < word.length(); i++) {
if (node.subNodes[word.charAt(i) - 'a'] != null) {
node = node.subNodes[word.charAt(i) - 'a'] ;
} else {
return false;
}
}
return node.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
MYTrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
if (node.subNodes[prefix.charAt(i) - 'a'] != null) {
node = node.subNodes[prefix.charAt(i) - 'a'] ;
} else {
return false;
}
}
return true;
}
}
實現前綴樹(增、判斷是否有該單詞,是否有該前綴)
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
- 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
推薦閱讀更多精彩內容
- 成長記錄-連載(三十六) ——我的第一篇五千字長文,說了什么,你一定想不到 并不是不想每天寫公眾號,而是之前思考怎...
- 20+個很棒的Android開源項目本文摘自文章: 20+ Awesome Open-Source Android...