648. Replace Words

Problem:
In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the rootforming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Note:
  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 1 <= sentence words length <= 1000

Analysis:
这道题是自己做出来的。
First build trie tree base on dict. Define TrieNode with word. Use word search II's approach. Whenever search meets node.word != null, we can make sure we find the shortest rootWord. 

Solution:

class Solution {
    public String replaceWords(List<String> dict, String sentence) {
        StringBuilder sb = new StringBuilder();
        String[] words = sentence.split(" ");
        TrieNode root = buildTrie(dict);
        
        for (String word: words) {
            TrieNode node = root;
            for (char c: word.toCharArray()) {
                if (node.children[c - 'a'] == null) {
                    break;
                }
                node = node.children[c - 'a'];
                if (node.word != null) break;
            }
            word = node.word == null ? word : node.word;
            sb.append(word + " ");
        }
        sb.setLength(sb.length () - 1);
        return sb.toString();
    }    
    
    private TrieNode buildTrie(List<String> dict) {
        
        TrieNode root = new TrieNode();
        for (String word: dict) {
            TrieNode node = root;
            for (char c: word.toCharArray()) {
                if (node.children[c - 'a'] == null) {
                    node.children[c - 'a'] = new TrieNode();
                }
                node = node.children[c - 'a'];
            }
            node.word = word;
        }
        return root;
    }
    
    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        String word;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List