前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 211. 添加与搜索单词 - 数据结构设计(Trie树)

LeetCode 211. 添加与搜索单词 - 数据结构设计(Trie树)

作者头像
Michael阿明
发布2020-07-13 15:30:33
3940
发布2020-07-13 15:30:33
举报

1. 题目

设计一个支持以下两种操作的数据结构:

void addWord(word) bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 .a-z. 可以表示任何一个字母。

代码语言:javascript
复制
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. Trie解题

  • 构建Trie树
  • 回溯查找,遇见.在所有的子树里查找,没有遇见.在,当前相等的情况下,再继续在所有的子树中递归查找
代码语言:javascript
复制
class TrieNode
{
public:
	char ch;
	TrieNode *next[26];
	bool isEnd;
	TrieNode(char c = '/'):ch(c),isEnd(false) 
	{
		memset(next, 0, sizeof(TrieNode*)*26);
	}
};
class Trie
{
public:
	TrieNode *root;
	Trie()
	{
		root = new TrieNode();
	}
	~Trie()
	{
		destroy(root);
	}
	void destroy(TrieNode *root)
	{
		if(root == NULL)
			return;
		for(int i = 0; i < 26; i++)
			destroy(root->next[i]);
		delete root;
	}
	void insert(string str)
	{
		TrieNode *cur = root;
		for(char s:str)
		{
			if(cur->next[s-'a'] == NULL)
				cur->next[s-'a'] = new TrieNode(s);
			cur = cur->next[s-'a'];
		}
		cur->isEnd = true;
	}
};
class WordDictionary {
	Trie tree;
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        tree.insert(word);
    }
    
    /** 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) {
    	TrieNode *cur = tree.root;
    	bool found = false;
    	for(int i = 0; i < 26; ++i)
    	{
	    	find(word,cur->next[i],0,found);
	    }
    	return found;
    }
    void find(string &word, TrieNode *root, int idx, bool &found)
    {
    	if(found || !root)
    		return;
    	if(idx == word.size()-1)
    	{
    		if(root->isEnd)
    			if(word[idx] == '.' || word[idx] == root->ch)
    				found = true;
    		return;
    	}
    	if((word[idx] != '.'&&root->ch == word[idx])
    			|| word[idx] == '.')
    	{	
            for(int i = 0; i < 26; ++i)
            {
                find(word,root->next[i],idx+1,found);
            }
    	}
    }
};
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. Trie解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档