211. Add and Search Word - Data structure design

Medium

这题讲真不是很懂

class TrieNode{
    HashMap<Character, TrieNode> children = new HashMap<>();
    char c;
    boolean isWord;
    public TrieNode(){
        
    }
    public TrieNode(char c){
        this.c = c;
    }
}

public class WordDictionary {
    public TrieNode root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        this.root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode curt = root;
        HashMap<Character, TrieNode> curtChildren = curt.children;
        for (int i = 0; i < word.length(); i++){
            char curtChar = word.charAt(i);
            if (curtChildren.containsKey(curtChar)){
                curt = curtChildren.get(curtChar);
            } else {
                TrieNode newNode = new TrieNode(curtChar);
                curtChildren.put(curtChar, newNode);
                curt = newNode;
            }
            curtChildren = curt.children;
            if (i == word.length() - 1){
                curt.isWord = 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) {
        return dfsSearch(word, 0, root);
    }
    
    public boolean dfsSearch(String s, int index, TrieNode curt){
        HashMap<Character, TrieNode> children = curt.children;
        if (index == s.length()){
            if (children.size() == 0){
                return true;
            } else {
                return false; 
            }
        }
        char c = s.charAt(index);
        if (children.containsKey(c)){
            if (index == s.length() - 1 && children.get(c).isWord){
                return true;
            }
            return dfsSearch(s, index + 1, children.get(c));
        } else if (c == '.'){
            boolean result = false;
            for (Map.Entry<Character, TrieNode> child : children.entrySet()){
                if (index == s.length() - 1 && child.getValue().isWord){
                    return true;
                }
                
                if (dfsSearch(s, index + 1, child.getValue())){
                    result = true;
                }
            }
            return result;
        } else {
            return false;
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容