LeetCode——Add and Search Word - Data structure design
Description:
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
.
题目很好理解:添加单词查找单词。
首先想到的是用线性数据结构,然后逐个匹配查找。可以想象一定是超时的。
public class WordDictionary { private List<String> arr = new ArrayList<String>(); // Adds a word into the data structure.
public void addWord(String word) {
arr.add(word);
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
boolean flag = true;
for(String str : arr) {
if(str.equals(word)) {
flag = true;
break;
}
else if(arr.contains(".")) {
if(word.length() != str.length()) {
flag = false;
break;
} for(int i=0; i<str.length();) {
char ch1 = str.charAt(i);
char ch2 = word.charAt(i);
if(ch1 == '.' || ch2 == '.' || ch1 == ch2) {
i ++;
}
else {
flag = false;
break;
}
} }
else {
flag = false;
break;
}
}
return flag;
}
} // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
要优化明显要使用Trie树来减少无用的比较次数,从而降低时间复杂度。
关于Trie树:http://www.cnblogs.com/wxisme/p/4876197.html
public class WordDictionary { private TrieNode root; public WordDictionary() {
this.root = new TrieNode();
} private class TrieNode {
private TrieNode[] son;
private char val;
private boolean isEnd;
public TrieNode() {
this.son = new TrieNode[26];
this.isEnd = false;
}
} // Adds a word into the data structure.
public void addWord(String word) { char[] wordChars = word.toCharArray();
TrieNode node = this.root; for(char ch : wordChars) {
int pos = ch - 'a';
if(node.son[pos] == null) {
node.son[pos] = new TrieNode();
node.son[pos].val = ch;
}
node = node.son[pos];
}
node.isEnd = true;
} public boolean patternSearch(String word, TrieNode node) {
char[] wordChars = word.toCharArray();
for(int at=0; at<word.length(); at++) {
char ch = wordChars[at];
if(ch != '.') {
int pos = ch - 'a';
if(node.son[pos] != null) { node = node.son[pos];
}
else {
return false;
}
}
else {
int flag = 0;
for(int i=0; i<26; i++) {
if(node.son[i] != null) {
boolean b =patternSearch(word.substring(at+1), node.son[i]);
if(b) return b;
else {
flag ++;
}
}
else {
flag ++;
continue;
}
}
if(flag == 26) {
return false;
}
}
}
return node.isEnd;
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) { return patternSearch(word, this.root);
} }
LeetCode——Add and Search Word - Data structure design的更多相关文章
- [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
- leetcode Add and Search Word - Data structure design
我要在这里装个逼啦 class WordDictionary(object): def __init__(self): """ initialize your data ...
- LeetCode Add and Search Word - Data structure design (trie树)
题意:实现添加单词和查找单词的作用,即实现字典功能. 思路:'.' 可以代表一个任何小写字母,可能是".abc"或者"a.bc"或者"abc.&quo ...
- leetcode面试准备:Add and Search Word - Data structure design
leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...
- 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design
字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...
- 【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 ...
- 【刷题-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 ...
- 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 ...
- Java for LeetCode 211 Add and Search Word - Data structure design
Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...
随机推荐
- Tslib步骤以及出现问题的解决方案(转)
嵌入式设备中触摸屏使用非常广泛,但触摸屏的坐标和屏的坐标是不对称的,需要校准.校准广泛使用的是开源的tslib. Tslib是一个开源的程序,能够为触摸屏驱动获得的采样提供诸如滤波.去抖.校准等功能, ...
- Dropwizard与Spring Boot比较
在这篇文章中我们将讨论的Java轻量级框架Dropwizard和Spring Boot的相似性和差异. 首先,这是一个选择自由和速度需要,无论你在Dropwizard和Spring Boot选择哪个, ...
- MySql 生成日期随机数
select DATE_ADD(sd, INTERVAL FLOOR(1+ RAND() * ((ABS(UNIX_TIMESTAMP(ed) - UNIX_TIMESTAMP(sd))) - 1)) ...
- linux设置开机服务自动启动/关闭自动启动命令
linux设置开机服务自动启动/关闭自动启动命令 2012-02-06 15:13 [root@localhost ~]# chkconfig --list 显示开机可以自动启动的服务[roo ...
- Struts2 的Action中取得请求参数值的几种方法
先看GetRequestParameterAction类代码: Java代码 public class GetRequestParameterAction extends ActionSupport ...
- java-基于Servlet3.0的文件上传
Servlet3.0学习总结(三)——基于Servlet3.0的文件上传 在Servlet3.0中使用request.getParts()获取上传文件
- php BC高精确度函数库
#两个高精度数比较 #int bccomp ( string $left_operand , string $right_operand [, int $scale ] ) #$left=$right ...
- C++构造函数后面的冒号
构造函数后加冒号是初始化表达式:有四种情况下应该使用初始化表达式来初始化成员:1:初始化const成员2:初始化引用成员3:当调用基类的构造函数,而它拥有一组参数时 4:当调用成员类的构造函数,而它拥 ...
- android 内存管理机制、异常、垃圾回收
当 Android 应用程序退出时,并不清理其所占用的内存,Linux 内核进程也相应的继续存在,所谓“退出但不关闭”.从而使得用户调用程序时能够在第一时间得到响应. 当系统内存不足时,系统将激活内存 ...
- python 向qq邮箱发邮件
#coding:utf-8 ''' Created on 2017-1-12 @author: xiaochun ''' import smtplib from email.mime.text imp ...