211. Add and Search Word


June-20-2019

多了个wildcard,无非是wildcard的时候下一层所有的NODE遍历一下。这个时候需要传下去substring和下层的node,所以多建了个search(string, node)
秒之

class WordDictionary {
    
    public class Node {
        Character letter;
        boolean isLetter;
        Map<Character, Node> nextLevel;
        
        public Node(Character letter) {
            nextLevel = new HashMap<>();
            this.letter = letter;
            this.isLetter = false;
        }
    }
    
    Node root;

    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new Node(null);
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        Node temp = root;
        for (int i = 0; i < word.length(); i ++) {
            char tempChar = word.charAt(i);
            if (!temp.nextLevel.containsKey(tempChar)) {
                temp.nextLevel.put(tempChar, new Node(tempChar));
            }
            temp = temp.nextLevel.get(tempChar);
        }
        temp.isLetter = 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 search(word, root);
    }
    
    public boolean search(String s, Node temp) {
        for (int i = 0; i < s.length(); i ++) {
            Character c = s.charAt(i);
            if (temp.nextLevel.containsKey(c)) {
                return search(s.substring(i + 1), temp.nextLevel.get(c));
            } else {
                if (c == '.') {
                    for (Map.Entry<Character, Node> entry : temp.nextLevel.entrySet()) {
                        if (search(s.substring(i + 1), entry.getValue())) return true;
                    }
                    return false;
                } else {
                    return false;
                }
            }
        }
        return temp.isLetter;
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/5877845.html