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. CKFinder 弹出窗口操作并设置回调函数

    CKFinder 弹出窗口操作并设置回调函数 官方例子参考CKFinderJava-2.4.1/ckfinder/_samples/popup.html 写一个与EXT集成的小例子 Ext.defin ...

  2. Apache HttpComponents 文件上传例子

    /* * ==================================================================== * * Licensed to the Apache ...

  3. 修改Linux内核参数,减少TCP连接中的TIME-WAIT

    一台服务器CPU和内存资源额定有限的情况下,如何提高服务器的性能是作为系统运维的重要工作.要提高Linux系统下的负载能力,当网站发展起来之后,web连接数过多的问题就会日益明显.在节省成本的情况下, ...

  4. ASP.NET 防止重复提交提示层

    今天研究了下,其实我希望的很简单,就是有个封装好的提示层,等处理完后,刷新界面时 能自动消失 找了挺久的,找到这个控件还不错 完整Demo地址: http://download.csdn.net/de ...

  5. PixelMatorPro快捷键大全(osx)

    Keyboard Shortcuts Navigate an image   Zoom in Command-Plus (+) Zoom out Command-Minus (-) Zoom to f ...

  6. Windows与Linux下进程间通信技术比较

    一般我们写的程序都是以单个进程的方式来运行的,比较少涉及到多进程.特别是在windows下,因为Windows是按照线程来分配CPU时间片的,线程是最小的调度单位,所以在Windows下更多的用到多线 ...

  7. 【转】ImageView的Scaletype参数设置

    ImageView的Scaletype决定了图片在View上显示时的样子,如进行何种比例的缩放,及显示图片的整体还是部分,等等. 设置的方式包括: 1. 在layout xml中定义Android:s ...

  8. 另外一款超棒的响应式布局jQuery插件 – Freetile.js

    在线演示 我们曾经介绍过俩款知名的响应式布局插:isotope和masonary,今天我们这里再介绍一款相当不错的响应式布局插件 – Freetile.js,使用它同样可以生成超酷的动态布局效果.相信 ...

  9. 自然语言交流系统 phxnet团队 创新实训 个人博客 (一)

    项目涉及链表操作,遂整理: 使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理.但是链表失去了数组随机读取的优点,同时链表由于增加了结点 ...

  10. 介绍Unity中相机的投影矩阵与剪切图像、投影概念

    这篇作为上一篇的补充介绍,主要讲Unity里面的投影矩阵的问题: 上篇的链接写给VR手游开发小白的教程:(三)UnityVR插件CardboardSDKForUnity解析(二) 关于Unity中的C ...