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的更多相关文章

  1. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

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

  2. leetcode Add and Search Word - Data structure design

    我要在这里装个逼啦 class WordDictionary(object): def __init__(self): """ initialize your data ...

  3. LeetCode Add and Search Word - Data structure design (trie树)

    题意:实现添加单词和查找单词的作用,即实现字典功能. 思路:'.' 可以代表一个任何小写字母,可能是".abc"或者"a.bc"或者"abc.&quo ...

  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 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

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

  6. 【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 ...

  7. 【刷题-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 ...

  8. 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  ...

  9. 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 ...

随机推荐

  1. [systemd]How To Use Systemctl to Manage Systemd Services and Units

    转自: https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services ...

  2. [uboot]What is MLO file?

    转自:https://coherentmusings.wordpress.com/2012/09/05/what-is-mlo-file/ I have had the Beagle-xM for a ...

  3. java-基于Servlet3.0的文件上传

    Servlet3.0学习总结(三)——基于Servlet3.0的文件上传 在Servlet3.0中使用request.getParts()获取上传文件

  4. 用大白话揭开Ajax长轮询(long polling)的神秘面纱

    在看这篇Ajax长轮询之前可以先看看Ajax轮询技术(没有长),有助于理解: Ajax长轮询属于Ajax轮询的升级版,在客户端和服务端都进行了一些改造,使得消耗更低,速度更快. "不间断的通 ...

  5. 将sqlServer上的数据库文件进行盘目的迁移

    在数据库客户端创建数据库时要改为.mdf文件,因为附加问价时附加的是.mdf文件: 在里选中相应的数据库 右键->任务-分离 在 剪切到相应的想放置的盘目. 例如迁移到E盘下: 在数据库-> ...

  6. 如何识别Java中的内存泄漏

    Java开发人员都知道,Java利用垃圾回收机制来自动保持应用程序内存的干净和健康.然而可能有人不知道的是,即使使用了垃圾回收机制,Java中仍然可能存在内存泄漏风险.如果你碰到下面的错误代码: ja ...

  7. MySQL无法远程连接解决方案

    1.查看/etc/mysql/my.cnf配置文件是否只允许本地连接 注释配置:#bind-address = 127.0.0.1,重启MySQL Server 2.防火墙(我用的是iptables) ...

  8. c++ 的vector、array和数组的比较

    ref:  http://blog.csdn.net/haust_wang/article/details/49848169

  9. Winform appconfig修改后的更新问题

  10. ThinkPHP的易忽视点小结

    1.使用对象的方法插入数据 D用法. $Form = D('Form'); $data['title'] = 'ThinkPHP'; $data['content'] = '表单内容'; $Form- ...