classTrieNode{ // Initialize your data structure here. boolean isLeaf; TrieNode[] nodes; publicTrieNode(){ isLeaf = false; nodes = new TrieNode[26]; } }
publicclassTrie{ private TrieNode root;
publicTrie(){ root = new TrieNode(); }
// Inserts a word into the trie. publicvoidinsert(String word){ TrieNode node = root; for(int i = 0; i < word.length(); ++i) { int index = word.charAt(i) - 'a'; /***错误的写法,node信息丢失 * node = node.nodes[index]; * if(node == null) * node = new TrieNode(); ***/ if(node.nodes[index] == null) node.nodes[index] = new TrieNode(); node = node.nodes[index]; if(i == word.length() - 1) node.isLeaf = true; } }
// Returns if the word is in the trie. publicbooleansearch(String word){ TrieNode node = root; for(int i = 0; i < word.length(); ++i) { int index = word.charAt(i) - 'a'; node = node.nodes[index]; if(node == null) returnfalse; if(i == word.length() - 1 && node.isLeaf) returntrue; } returnfalse; }
// Returns if there is any word in the trie // that starts with the given prefix. publicbooleanstartsWith(String word){ TrieNode node = root; for(int i = 0; i < word.length(); ++i) { int index = word.charAt(i) - 'a'; node = node.nodes[index]; if(node == null) returnfalse; } returntrue; } }
// Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example, Given words = [“oath”,”pea”,”eat”,”rain”] and board =
[ [‘o’,’a’,’a’,’n’], [‘e’,’t’,’a’,’e’], [‘i’,’h’,’k’,’r’], [‘i’,’f’,’l’,’v’] ] Return [“eat”,”oath”]. Note: You may assume that all inputs are consist of lowercase letters a-z. https://leetcode.com/problems/word-search-ii/