211.添加与搜索单词

题目描述

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

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

示例:

addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(".ad") -> true
search(“b…”) -> true
说明:

你可以假设所有单词都是由小写字母 a-z 组成的。


解答

  • 插入为常规前缀树
  • 搜索引入了通识符,要用递归逐个尝试
    • search
      • 创建节点->调用dfs
    • dfs
      • 终止条件,len=word.length()
      • 过程,获取字符->判断
        • 非通识符,若非空,则进入下一层递归,否则返回false
        • 通识符,逐个尝试,非空且进入下层最终获取终止,则返回true
          • 逐个尝试后未得到true,则最终返回false
class WordDictionary {
    private boolean isEnd=false;
    private WordDictionary next[]=new WordDictionary[26];
    /** Initialize your data structure here. */
    public WordDictionary() {}
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        WordDictionary root=this;
        for(char ch:word.toCharArray()){
            if(root.next[ch-'a']==null){
                root.next[ch-'a']=new WordDictionary();
            }
            root=root.next[ch-'a'];
        }
        root.isEnd=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) {
        WordDictionary root=this;
        return dfs(root,word,0);
    }
    public boolean dfs(WordDictionary root,String word,int index){
        if(index==word.length()){
            return root.isEnd;
        }
        char ch=word.charAt(index);
        //不为.数组上也不为空,则递归进入下一个节点
        if(ch!='.'){
            if(root.next[ch-'a']!=null){
                return dfs(root.next[ch-'a'],word,index+1);
            }
            //若为空,则返回false;
            return  false;
        }
        //逐个尝试,不为空且递归后找到符合的串(返回true),则true
        for(WordDictionary next:root.next){
            if(next!=null&&dfs(next,word,index+1)){
                return  true;
            }
        }
        return  false;
    }
}
发布了13 篇原创文章 · 获赞 0 · 访问量 302

猜你喜欢

转载自blog.csdn.net/m0_37605197/article/details/105021050