211. Design Add and Search Words Data Structure

Photo by Sandro Gonzalez on Unsplash
Photo by Sandro Gonzalez on Unsplash
此題要我們建立一個 word dictionary,這很明顯就是要使用 Trie。不過題目還要可以支援 dots ‘.’。在搜尋的時候,它可以匹配任何字元。
Table of Contents
  1. Problem
  2. Solution
    1. Trie
  3. 參考

Problem

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

Example:

Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

Solution

此題要我們建立一個 word dictionary,這很明顯就是要使用 Trie。不過題目還要求支援 dots '.'。在搜尋的時候,它可以匹配任何字元。因此,當遇到 '.' 的時候,我們必須要搜尋該 node 的所有 children,直到找到匹配的字串。

Trie

class WordDictionary {
    class TrieNode {
        private Map<Character, TrieNode> children = new HashMap<>();
        private char character;
        private boolean terminates = false;

        TrieNode() {
        }

        TrieNode(char character) {
            this.character = character;
        }

        void addWord(String word) {
            if (word == null || word.isEmpty()) return;

            char firstChar = word.charAt(0);
            TrieNode child = children.get(firstChar);
            if (child == null) {
                child = new TrieNode(firstChar);
                children.put(firstChar, child);
            }
            if (word.length() > 1) {
                child.addWord(word.substring(1));
            } else {
                child.setTerminates(true);
            }
        }

        boolean search(String word) {
            if (word == null || word.isEmpty()) return false;

            char firstChar = word.charAt(0);
            if (firstChar == '.') {
                String subWord = word.substring(1);
                if (subWord.isEmpty()) {
                    for (TrieNode child : children.values()) {
                        if (child.terminates) {
                            return true;
                        }
                    }
                } else {
                    for (TrieNode child : children.values()) {
                        if (child.search(subWord)) {
                            return true;
                        }
                    }
                }
            } else {
                if (children.containsKey(firstChar)) {
                    TrieNode child = children.get(firstChar);
                    if (word.length() == 1) {
                        return child.terminates;
                    } else {
                        return child.search(word.substring(1));
                    }
                }
            }
            return false;
        }

        void setTerminates(boolean terminates) {
            this.terminates = terminates;
        }
    }

    private TrieNode root = new TrieNode();

    public WordDictionary() {
    }
    
    public void addWord(String word) {
        root.addWord(word);
    }
    
    public boolean search(String word) {
        return root.search(word);
    }
}

參考

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

You May Also Like
Photo by Oladimeji Odunsi on Unsplash
Read More

72. Edit Distance

在解此題時,我們要先觀察 word1 如何變成 word2。以 Example1 為例,左下圖列出 “horse” 轉變成 “ros” 的 distance。表中,縱軸表示 “horse”,而橫軸表示 “ros”。
Read More
Photo by Diana Parkhouse on Unsplash
Read More

1048. Longest String Chain

此題中,wordA 是 wordB 的 predecessor 指只要插入一個 letter 到 wordA,那就會使得它和 wordB 一樣。然而,插入一個 letter 到一個地方,就要考慮 26 種字母。這使得整體的複雜度上升。
Read More
Photo by Bogdan Farca on Unsplash
Read More

39. Combination Sum

此題要我們列出所有可能的組合,所以我們可能用 backtracking 來找。但是,我們必須避免找到相同的組合。當兩個組合裡的數字和個數都依一樣,但順序不一樣時,他們依然是相同的組合。
Read More