leetcode [211] Add and Search Word - Data structure design

本文介绍了一种使用前缀树(Trie)的数据结构来实现词典中单词的快速搜索,包括常规单词和包含通配符'.'的正则表达式字符串的搜索。通过构建前缀树,我们可以高效地添加和搜索单词,其中'.'可以匹配任何单个字符。

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.

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.

题目大意:

判断一个词是否在字典中出现过,其中词包括a-z和.这27个字符,其中.可以匹配任意字符。

解法:

使用前缀树做,根据单词建立一颗前缀树。

java:

class TrieNode{
    public char val;
    public boolean isWord;
    public TrieNode[] children=new TrieNode[26];
    TrieNode(){}
    TrieNode(char val){
        this.val=val;
    }
}

class WordDictionary {
    private TrieNode root;

    /** Initialize your data structure here. */
    public WordDictionary() {
        root=new TrieNode(' ');
    }

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode node=root;
        for(int i=0;i<word.length();i++) {
            char c = word.charAt(i);
            if (node.children[c - 'a'] == null) {
                node.children[c - 'a']=new TrieNode(c);
            }
            if(i==word.length()-1) node.children[c - 'a'].isWord=true;
            node = node.children[c - 'a'];
        }
    }

    private boolean helper(String word,TrieNode curNode,int index){
        if(index==word.length()){
            if(curNode.isWord) return true;
            else return false;
        }
        char c=word.charAt(index);
        if(c!='.' && curNode.children[c-'a']!=null){
            return helper(word,curNode.children[c-'a'],index+1);
        }else if(c!='.' && curNode.children[c-'a']==null){
            return false;
        }else{
            for(int i=0;i<26;i++){
                if(curNode.children[i]!=null){
                    if(helper(word,curNode.children[i],index+1)) return true;
                }
            }
            return false;
        }
    }

    /** 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) {
        TrieNode node=root;
        return helper(word,root,0);
    }
}

  

转载于:https://www.cnblogs.com/xiaobaituyun/p/10782612.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值