Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z

solution:

class TrieNode {
// Initialize your data structure here.
boolean isEnd; //是否有单词以该字母结尾
TrieNode[] sons; //子节点[a-z]
char value; //保存该节点代表的字母值 public TrieNode() {
isEnd = false;
sons = new TrieNode[26];
}
} public class Trie {
private TrieNode root; public Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
/**
* 对于传入的单词,从左往右遍历每个字母,依次从根节点向下建树
* 每个节点保存一个字母
* @param word
*/
public void insert(String word) {
if (word == null || word.length() == 0)
return;
TrieNode p = root; //工作指针,初始指向根节点
for (int i = 0; i < word.length(); i++) {
int pos = word.charAt(i) - 'a'; //hash-计算该字母对应的位置
if (p.sons[pos] == null) { //判断该位置是否为空
p.sons[pos] = new TrieNode();
p.sons[pos].value = word.charAt(i);
}
p = p.sons[pos]; //指向子节点
}
p.isEnd = true; //标记该节点,表示有单词以之结尾
} // Returns if the word is in the trie.
/**
* 类似建树过程,从左往右简历单词的每个字母,如果对应位置为空,则表示树中
* 不存在该单词
* @param word
* @return
*/
public boolean search(String word) {
if (word == null || word.length() == 0)
return false;
TrieNode p = root;
for (int i = 0; i < word.length(); i++) {
int pos = word.charAt(i) - 'a';
if (p.sons[pos] == null)
return false;
p = p.sons[pos];
}
return p.isEnd; //false表示所查单词是树中某个单词的前缀,但不完全匹配
} // 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 p = root;
for (int i = 0; i < prefix.length(); i++) {
int pos = prefix.charAt(i) - 'a';
if (p.sons[pos] == null)
return false;
p = p.sons[pos];
}
return true;
}
} // Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

Add and Search Word

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

solution:

public class WordDictionary {

    private Tode root;

    public WordDictionary() {
root = new Tode();
} // Adds a word into the data structure.
/**
* 与上题一致
* @param word
*/
public void addWord(String word) {
if(word == null || word.length() == 0)
return ;
Tode p = root;
for(int i=0; i<word.length(); i++){
int pos = word.charAt(i) - 'a';
if(p.sons[pos] == null){
p.sons[pos] = new Tode();
p.sons[pos].value = word.charAt(i);
}
p = p.sons[pos];
}
p.isEnd = true;
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
/**
* 因为.能匹配所有字母,导致不能直接hash判断字母是否存在,而必须对树进行深度优先遍历。
* @param word
* @return
*/
public boolean search(String word) {
if(word == null || word.length() == 0)
return false;
char[] arr = word.toCharArray();
int index = 0;
Tode p = root;
return goSearch(arr, index, p);
} private boolean goSearch(char[] arr, int index, Tode p) {
if(index == arr.length)
return p.isEnd;
if(arr[index] == '.'){
for(Tode n : p.sons){ //搜索当前节点的所有非空子节点
if(n != null && goSearch(arr, index+1, n)) //若有节点搜索到匹配单词,则直接返回
return true;
}
return false;
}else{
int pos = arr[index] - 'a';
if(p.sons[pos] != null)
return goSearch(arr, index+1, p.sons[pos]);
else
return false;
}
} class Tode{
boolean isEnd;
Tode[] sons;
char value;
public Tode(){
isEnd = false;
sons = new Tode[26];
}
}
} // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

(Data structure)Implement Trie && Add and Search Word的更多相关文章

  1. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  2. LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design

    字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith  ...

  3. 【LeetCode】211. Add and Search Word - Data structure design

    Add and Search Word - Data structure design Design a data structure that supports the following two ...

  4. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  5. 【刷题-LeetCode】211. Add and Search Word - Data structure design

    Add and Search Word - Data structure design Design a data structure that supports the following two ...

  6. [LintCode] Add and Search Word 添加和查找单词

    Design a data structure that supports the following two operations: addWord(word) and search(word) s ...

  7. leetcode 211. Add and Search Word - Data structure design Trie树

    题目链接 写一个数据结构, 支持两种操作. 加入一个字符串, 查找一个字符串是否存在.查找的时候, '.'可以代表任意一个字符. 显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可 ...

  8. [leetcode trie]211. Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  9. (*medium)LeetCode 211.Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

随机推荐

  1. 使用powershell监控命令行console程序并在停止时启动

    有一种C#命令行console程序,为了能看到console台的输出所以不能做成服务.为了防止这些程序自己死掉,使用powershell监控程序并重启 #利用程序名来进行重启if (!(get-pro ...

  2. (转)关于Android的nodpi,xhdpi,hdpi,mdpi,ldpi

    首先是几个基本概念:1.屏幕尺寸Screen size即显示屏幕的实际大小,按照屏幕的对角线进行测量.为简单起见,Android把所有的屏幕大小分为四种尺寸:小,普通,大,超大(分别对应:small, ...

  3. XML解析器(TinyXML)的使用指南

    关于XML文件的解析方法的引导, 大家可以去试试这个工具(TinyXML) 1.首先下载TinyXML库的文件,这里给出链接,大家自己去下吧,记着要上国际http://prdownloads.sour ...

  4. C#去除byte数组头尾杂质(即不需要的数据)

    代码如下: /// <summary> /// 去除byte数组头尾杂质(即不需要的数据) /// </summary> /// <param name="ar ...

  5. zabbix监控应用连接数

    zabbix使用用户自定义键值来监控应用系统连接数: 1.修改配置文件zabbix_agentd.conf 格式: UserParameter=<key>,<shell comman ...

  6. thinkphp学习资料

    http://www.5idev.com/p-thinkphp_auto_function_callback.shtml

  7. 关于ubuntu16.04给firefox安装flash的补充

    这两天把自己的老笔记本安装了ubuntu的16.04版本,关于给firefox安装flash player的方法,网上有很多,但不知道是版本还是其它原因,他们文章都出现目录错误的问题,我个人由于是ub ...

  8. iframe 元素

    iframe 元素会创建包含另外一个文档的内联框架(即行内框架). 可以访问:http://www.w3school.com.cn/tags/tag_iframe.asp

  9. python 下的数据结构与算法---5:递归(Recursion)

    定义:递归就是不断分割整体成部分直到可以轻易解决分割出来的部分. 递归表达式三定律: 1:递归表达式必须有个最小单元     (最小单元既是停止递归调用以及能够直接运算的) 2:递归表达式在运算过程中 ...

  10. C#中的switch case

    在C#中switch(type){case tpye1:break;case tpye2:break;case tpye3:break;case tpye4:break;};其中type可以是数字,也 ...