All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0212_word_search_ii.Tree Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0201_0300.s0212_word_search_ii;

// #Hard #Top_Interview_Questions #Array #String #Matrix #Backtracking #Trie
// #2022_07_02_Time_21_ms_(99.42%)_Space_44.1_MB_(67.33%)

/**
 * 212 - Word Search II\.
 *
 * Hard
 *
 * Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
 *
 * Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/11/07/search1.jpg)
 *
 * **Input:** board = \[\["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
 *
 * **Output:** ["eat","oath"] 
 *
 * **Example 2:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/11/07/search2.jpg)
 *
 * **Input:** board = \[\["a","b"],["c","d"]], words = ["abcb"]
 *
 * **Output:** [] 
 *
 * **Constraints:**
 *
 * *   `m == board.length`
 * *   `n == board[i].length`
 * *   `1 <= m, n <= 12`
 * *   `board[i][j]` is a lowercase English letter.
 * *   1 <= words.length <= 3 * 104
 * *   `1 <= words[i].length <= 10`
 * *   `words[i]` consists of lowercase English letters.
 * *   All the strings of `words` are unique.
**/
@SuppressWarnings("java:S1104")
public class Tree {
    private Tree[] children;
    public String end;
    private int length = 0;

    private Tree addChild(char c) {
        int i = c - 'a';
        if (children == null) {
            children = new Tree[26];
        }
        if (children[i] == null) {
            children[i] = new Tree();
            ++length;
        }
        return children[i];
    }

    public Tree getChild(char c) {
        return (children == null) ? null : children[c - 'a'];
    }

    public int len() {
        return length;
    }

    public static void addWord(Tree root, String word) {
        Tree t = root;
        for (char c : word.toCharArray()) {
            t = t.addChild(c);
        }
        t.end = word;
    }

    public static void deleteWord(Tree root, String word) {
        Tree toDelOn = root;
        char toDel = word.charAt(0);
        for (char c : word.toCharArray()) {
            if (root.length > 1) {
                toDelOn = root;
                toDel = c;
            }
            root = root.getChild(c);
            if (root == null) {
                throw new IllegalArgumentException();
            }
        }
        toDelOn.children[toDel - 'a'] = null;
        --toDelOn.length;
        if (root.length != 0) {
            throw new IllegalArgumentException();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy