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 ...
随机推荐
- [mmc]Linux下MMC/SD/SDIO的识别与操作
转自:http://blog.csdn.net/skdkjzz/article/details/38927943 我们知道host在扫描卡的过程中,其识别的顺序为SDIO SD MMC,并且从它的注 ...
- ReentrantReadWriteLock锁例子
锁所提供的最重要的改进之一就是ReadWriteLock接口和唯一 一个实现它的ReentrantReadWriteLock类.这个类提供两把锁,一把用于读操作和一把用于写操作.同时可以有多个线程执行 ...
- C++实现八皇后问题
C++实现八皇后问题 #include <iostream> using std::cout; using std::endl; #include <iomanip> usin ...
- umount 强制卸载
umount -lf /mnt 强制卸载文件 -f Force unmount (in case of an unreachable NFS system). (Requires kern ...
- [oracle] 如何使用myBatis在数据库中插入数据并返回主键
在MyBatis中,希望在Oracle中插入数据的同时返回主键值,而非插入的条数. ① oracle使用 selectKey. U_USER_INFO_SEQ 是在数据库中定义好的这张表关联的序列se ...
- [android] Android 错误集锦
问题1:导入工程时报错The import android.XXX cannot be resolved 解决方法: 1.右键工程→Bulid Path→Configure Build Path... ...
- Java logger组件:slf4j, jcl, jul, log4j, logback, log4j2
先说结论 建议优先使用logback 或 log4j2.log4j2 不建议和 slf4j 配合使用,因为格式转换会浪费性能. 名词:jcl 和 jul 标题中的 jcl 是 apache Jakar ...
- CMutex、CCriticalSection、CSemaphore、CEvent、WaitForSingleObject 的小例子
一.CMutex CMutex mutex; mutex.Lock(); // 互斥的动作 // mutex.Unlock(); 二.CCriticalSection CCriticalSection ...
- 用C结构体来实现面向对象编程,ti xDAIS标准算法就这么搞的(1)
用C结构体来实现面向对象编程,ti xDAIS标准算法就这么搞的. 测试代码如下: #include <stdio.h> #include <stdlib.h> #includ ...
- FFmpeg在Android上的移植优化步骤
http://blog.csdn.net/feixiang_john/article/details/7894188 从事多媒体软件开发的人几乎没有不知道FFmpeg的,很多视频播放器都是基于FFmp ...