Scribbling

[Java 101] 211. Design Add and Search Words Data Structure - trie 본문

Computer Science/Java

[Java 101] 211. Design Add and Search Words Data Structure - trie

focalpoint 2023. 3. 11. 01:09
class TrieNode {
    public boolean isWord = false;
    public TrieNode[] children = new TrieNode[26];
}

class Trie {
    public TrieNode root;
    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode cur = root;
        for (int i=0; i<word.length(); i++) {
            char c = word.charAt(i);
            if (cur.children[c - 'a'] == null) cur.children[c - 'a'] = new TrieNode();
            cur = cur.children[c - 'a'];
        }
        cur.isWord = true;
    }

    public boolean search(String word) {
        return _search(root, word);
    }

    public boolean _search(TrieNode node, String word) {
        if (word.isEmpty()) {
            return node.isWord;
        }
        char c = word.charAt(0);
        if (c == '.') {
            for (char l='a'; l<='z'; l++) {
                if (node.children[l - 'a'] != null) {
                    if (_search(node.children[l - 'a'], word.substring(1))) {
                        return true;
                    }
                }
            }
            return false;
        } else {
            if (node.children[c - 'a'] == null) return false;
            return _search(node.children[c - 'a'], word.substring(1));
        }
    }
}

class WordDictionary {

    Trie t;
    
    public WordDictionary() {
        t = new Trie();
    }

    public void addWord(String word) {
        t.insert(word);
    }

    public boolean search(String word) {
        return t.search(word);
    }
}