LeetCode 211 Add and Search Word - Data structure design
2015-12-08 11:10
603 查看
题目描述
Design a data structure that supports the following two operations:[code]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:
[code]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.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
分析
本题只能用Trie,但是……LeetCode最近加入了一个测试用例,我试了所有网上能找到的代码,都是Time Limit Exceeded!代码
[code] class TrieNode { boolean isLeaf; char c; HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>(); // Initialize your data structure here. public TrieNode() { } public TrieNode(char c) { this.c = c; } } public class WordDictionary { private TrieNode root; public WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. public void addWord(String word) { HashMap<Character, TrieNode> children = root.children; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); TrieNode t; if (children.containsKey(c)) { t = children.get(c); } else { t = new TrieNode(c); children.put(c, t); } children = t.children; if (i == word.length() - 1) { t.isLeaf = true; } } } // 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 searchNode(word, root); } private boolean searchNode(String word, TrieNode t) { if (t == null) { return false; } if (word.length() == 0) { return t.isLeaf; } HashMap<Character, TrieNode> children = t.children; char c = word.charAt(0); if (c == '.') { for (char key : children.keySet()) { if (word.length() == 1 && children.get(key).isLeaf) { return true; } if (searchNode(word.substring(1), children.get(key))) { return true; } } return false; } else if (!children.containsKey(c)) { return false; } else { return searchNode(word.substring(1), children.get(c)); } } } // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary = new WordDictionary(); // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- cygwin gcc 动态链接库问题
- saltstack相关
- Something
- 图像滤镜艺术---乐高像素拼图特效滤镜的代码实现
- 源码安装lamp
- Objc-C 知识点回顾 六 字典、集合
- Gosn的使用
- leetcode -- Lowest Common Ancestor of a Binary Tree -- 重点
- opencv中的矩阵操作
- db2 外置设备建立数据库步骤
- 【Codeforces Round 271 (Div 2)D】【DP】Flowers 黑色必须连续摆放k,长度为n的摆放方案数
- SWD与JTAG之间的区别
- Objc-C 知识点回顾 五 NSArray、NSMutableArray
- 慕课网:Android异步加载AsyncTask项目实战中
- Java 中有关数组的操作
- MongoDB学习(二):数据类型和基本概念
- 允许php执行linux命令
- Day_7访问权限
- Kafka(二) -- Kafka 用在哪
- ADMT3.2域迁移之Server2003至Server2012系列(九)用户迁移