美文网首页
211. Add and Search Word - Data

211. Add and Search Word - Data

作者: 尚无花名 | 来源:发表于2019-04-20 09:55 被阅读0次

    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.
    这题是Trie的基本操作。
    我的经验是把Trie的操作提取出来,像这里面的 getOrCreate这个函数。
    这样逻辑就简化很多了。
    其它的就挺直接的这里就不多说了。

    class WordDictionary {
        TrieNode root;
        /** Initialize your data structure here. */
        public WordDictionary() {
            root = new TrieNode('a');
        }
        
        /** Adds a word into the data structure. */
        public void addWord(String word) {
            TrieNode cur = root;
            for (char c : word.toCharArray()) {
                cur = cur.getOrCreate(c);
            }
            cur.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 helper(root, word, 0);
        }
        private boolean helper(TrieNode root, String word, int index) {
            if (root == null) return false;
            if (index == word.length()) {
                return root.isWord;
            }
            if (word.charAt(index) != '.') {
                return helper(root.get(word.charAt(index)), word, index + 1);
            } else {
                for (char c = 'a'; c <= 'z'; c++) {
                    if (helper(root.get((char) c), word, index + 1)) return true;
                }
                return false;
            }
        }
    }
    class TrieNode {
        char c;
        boolean isWord;
        TrieNode[] child;
        public TrieNode(char c) {
            this.c = c;
            child = new TrieNode[26];
        }
        public TrieNode getOrCreate(char c) {
            if (child[c - 'a'] == null) {
                child[c - 'a'] = new TrieNode(c);
            }
            return get(c);
        }
        public TrieNode get(char c) {
            return child[c - 'a'];
        }
    }
    
    

    相关文章

      网友评论

          本文标题:211. Add and Search Word - Data

          本文链接:https://www.haomeiwen.com/subject/dfrkgqtx.html