博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-211 Add and Search Word - Data structure design
阅读量:4593 次
发布时间:2019-06-09

本文共 2121 字,大约阅读时间需要 7 分钟。

题目描述

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.

 

题目大意

实现两个操作:插入单词、查找单词(查找单词时的输入只能为 'a-z' 和 '.' ,其中 '.' 可以代表任何小写字母)。

 

示例

E

addWord("bad")addWord("dad")addWord("mad")search("pad") -> falsesearch("bad") -> truesearch(".ad") -> truesearch("b..") -> true

 

解题思路

解题思路类似于LeetCode - 208 Implement Trie,设置一个node class用来记录保存树结点中的节点信息。

插入单词是建树的过程,查找单词是搜索树的过程。

 

复杂度分析

时间复杂度:O(N)

空间复杂度:O(N)

 

代码

class TrieNode {public:    //该节点代表的字母是否是某个单词的最后一个字母    bool word;    TrieNode* children[26];    TrieNode() {        word = false;        memset(children, NULL, sizeof(children));    }};class WordDictionary {public:    /** Initialize your data structure here. */    WordDictionary() {            }        //建立一棵树    /** Adds a word into the data structure. */    void addWord(string word) {        TrieNode* node = root;        for (char c : word) {            if (!node -> children[c - 'a']) {                node -> children[c - 'a'] = new TrieNode();            }            node = node -> children[c - 'a'];        }        node -> word = true;    }        /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */    bool search(string word) {        return search(word.c_str(), root);    }private:    TrieNode* root = new TrieNode();        bool search(const char* word, TrieNode* node) {        for (int i = 0; word[i] && node; i++) {            //若搜索的单词该位置不是‘.’,则直接进行比较,否则对所有子结点进行遍历搜索            if (word[i] != '.') {                node = node -> children[word[i] - 'a'];            } else {                TrieNode* tmp = node;                for (int j = 0; j < 26; j++) {                    node = tmp -> children[j];                    if (search(word + i + 1, node)) {                        return true;                    }                }            }        }        return node && node -> word;    }};

 

转载于:https://www.cnblogs.com/heyn1/p/11050365.html

你可能感兴趣的文章
ued.taobao.com
查看>>
香港身份证
查看>>
(二)Python selenium
查看>>
7.装饰器的一些需求
查看>>
优雅就一个字——设计模式之数据上传接口
查看>>
js 数组中sort方法存在的问题
查看>>
Machine Learning - 第7周(Support Vector Machines)
查看>>
Zookeeper注册节点的掉线自动重新注册及测试方法
查看>>
【SVM】清晰明了的理论文章
查看>>
C#学习笔记_02_数据类型
查看>>
Flutter实战视频-移动电商-40.路由_Fluro的全局注入和使用方法
查看>>
ddd
查看>>
Excel 2013中设置密码保护表格数据不被修改的方法
查看>>
Flash中的隔离沙箱
查看>>
即点即用:在 21 世纪交付 Office
查看>>
AJAX表单提交以及数据接收
查看>>
用tensorflow学习贝叶斯个性化排序(BPR)
查看>>
ADO.NET的记忆碎片(四)
查看>>
浏览器的渲染过程
查看>>
小组项目冲刺第三天每日站立会议
查看>>