[LeetCode][JavaScript]Add and Search Word - Data structure design
2015-07-12 20:45
716 查看
Add and Search Word - Data structure design
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-zor
.. 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.
https://leetcode.com/problems/add-and-search-word-data-structure-design/
字典树,在上一题的基础上稍做修改。/article/7170972.html
遇到'.'就要采用递归的方式,遍历这一层词典里所有的词。
/** * @constructor */ var WordDictionary = function() { this.root = new TrieNode('root'); }; function TrieNode(key) { return { key : key, isWord : false }; } /** * @param {string} word * @return {void} * Adds a word into the data structure. */ WordDictionary.prototype.addWord = function(word) { var tree = this.root, i, curr; for(i = 0; i < word.length; i++){ curr = word[i]; if(!tree[curr]){ tree[curr] = new TrieNode(curr); } tree = tree[curr]; } tree.isWord = true; }; /** * @param {string} word * @return {boolean} * Returns if the word is in the data structure. A word could * contain the dot character '.' to represent any one letter. */ WordDictionary.prototype.search = function(word) { return searchWord(word, this.root); function searchWord(word, tree){ if(word === "" && tree.isWord){ return true; } if(word[0] !== '.'){ if(!tree[word[0]]){ return false; }else{ return searchWord(word.substring(1, word.length), tree[word[0]]); } }else{ for(var i in tree){ if(i === 'key' || i === 'isWord'){ continue; } if(searchWord(word.substring(1, word.length), tree[i])){ return true; } } return false; } } };
相关文章推荐
- js匿名函数实现递归调用
- js中select动态添加option
- 【S2第二学期-使用JSP/Servlet技术开发新闻发布系统】全书知识点总结
- js实现倒数计时器功能
- [LeetCode][JavaScript]Lowest Common Ancestor of a Binary Search Tree
- json java/ javascript
- javascript格式化table标签内容
- 图解Javascript上下文与作用域
- JS面向对象的程序设计
- CommonJS是什么
- JS闭包的理解
- JSF入门教程
- js 返回页面顶部
- javascript跨域访问探索之旅
- 2015.7.7js-07-2(基础)
- javascript变量声明提升
- JavaScript作用域链
- JSP中EL表达式入门与简介
- 1013: [JSOI2008]球形空间产生器sphere
- JavaScript 中值得注意的要点(1)