Showing posts with label Trie. Show all posts
Showing posts with label Trie. Show all posts

Sunday, July 16, 2017

212. 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.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.



Solution:

We use a Trie to store all valid words.

Then use DFS to try if any word is valid in the board.



Code:


public class Solution {
    
    class TrieNode {
        TrieNode[] link;
        String word;
        public TrieNode() {
            this.link = new TrieNode[26];
            this.word = null;
        }
    }
    
    public List<String> findWords(char[][] board, String[] words) {
        List<String> result = new ArrayList<>();
        if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
            return result;
        }
        if (words == null || words.length == 0) {
            return result;
        }
        TrieNode root = buildTrie(words);
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                dfs(board, root, i, j, result);
            }
        }
        return result;
    }
    
    public TrieNode buildTrie(String[] words) {
        TrieNode root = new TrieNode();
        for (String word : words) {
            TrieNode curr = root;
            for (char c : word.toCharArray()) {
                if (curr.link[c - 'a'] == null) {
                    curr.link[c - 'a'] = new TrieNode();
                }
                curr = curr.link[c - 'a'];
            }
            curr.word = word;
        }
        return root;
    }
    
    public void dfs(char[][] board, TrieNode curr, int i, int j, List<String> result) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return;
        }
        char c = board[i][j];
        if (c == '#' || curr.link[c - 'a'] == null) {
            return;
        }
        curr = curr.link[c - 'a'];
        if (curr.word != null) {
            result.add(curr.word);
            curr.word = null;
        }
        board[i][j] = '#';
        dfs(board, curr, i - 1, j, result);
        dfs(board, curr, i + 1, j, result);
        dfs(board, curr, i, j - 1, result);
        dfs(board, curr, i, j + 1, result);
        board[i][j] = c;
    }
}

Friday, May 26, 2017

211. Add and Search Word - Data structure design

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.
For 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.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.



Solution:

The idea is to implement a Trie to store the words.

The tricky part is to handle ".".

When we meet a ".", we just try all 26 possible characters and check if from any one we can get find this word.



Code:


public class WordDictionary {
    
    class TrieNode {
        public TrieNode[] link;
        public boolean isEnd;
        public TrieNode() {
            link = new TrieNode[26];
            for (int i = 0; i < 26; i++) {
                link[i] = null;
            }
            this.isEnd = false;
        }
    }

    private TrieNode root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode();
        
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode curr = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (curr.link[c - 'a'] == null) {
                curr.link[c - 'a'] = new TrieNode();
            }
            curr = curr.link[c - 'a'];
        }
        curr.isEnd = 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 find(word, root, 0);
    }
    
    public boolean find(String word, TrieNode root, int index) {
        if (index == word.length()) {
            return root.isEnd;
        }
        char c = word.charAt(index);
        if (c == '.') {
            for (int i = 0; i < 26; i++) {
                if (root.link[i] != null) {
                    if (find(word, root.link[i], index + 1)) {
                        return true;
                    }
                }
            }
            return false;
        }
        else if (root.link[c - 'a'] != null){
            return find(word, root.link[c - 'a'], index + 1);
        }
        else {
            return false;
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */

Sunday, May 7, 2017

208. Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.



Solution:



Code:


public class Trie {
    class TrieNode {
        private TrieNode[] links;
        private int R = 26;
        private boolean isEnd;
        public TrieNode() {
            links = new TrieNode[R];
        }
        
        public boolean containsKey(char c) {
            return links[c - 'a'] != null;
        }
        
        public TrieNode get(char c) {
            return links[c - 'a'];
        }
        
        public void put(char c, TrieNode node) {
            links[c - 'a'] = node;
        }
        
        public void setEnd() {
            isEnd = true;
        }
        
        public boolean isEnd() {
            return isEnd;
        }
    }
    
    private TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!node.containsKey(c)) {
                node.put(c, new TrieNode());
            }
            node = node.get(c);
        }
        node.setEnd();
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = searchPrefix(word);
        return node != null && node.isEnd();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix);
        return node != null;
    }
    
    public TrieNode searchPrefix(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.containsKey(c)) {
                node = node.get(c);
            }
            else {
                return null;
            }
        }
        return node;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */




public class Trie {

    class TrieNode {
        public TrieNode[] link;
        public boolean isEnd;
        public TrieNode() {
            this.link = new TrieNode[26];
            for (int i = 0; i < 26; i++) {
                this.link[i] = null;
            }
            this.isEnd = false;
        }
    }
    
    public TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode curr = root;
        for (char c : word.toCharArray()) {
            if (curr.link[c - 'a'] == null) {
                curr.link[c - 'a'] = new TrieNode();
            }
            curr = curr.link[c - 'a'];
        }
        curr.isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode curr = root;
        for (char c : word.toCharArray()) {
            if (curr.link[c - 'a'] == null) {
                return false;
            }
            else {
                curr = curr.link[c - 'a'];
            }
        }
        return curr.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode curr = root;
        for (char c : prefix.toCharArray()) {
            if (curr.link[c - 'a'] == null) {
                return false;
            }
            else {
                curr = curr.link[c - 'a'];
            }
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */