648. Replace Words

Description

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 root forming 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

Solution

Trie

class Solution {
    public String replaceWords(List dict, String sentence) {
        if (dict == null || dict.isEmpty() 
            || sentence == null || sentence.isEmpty()) {
            return sentence;
        }
        
        Trie trieRoot = new Trie();
        for (String word : dict) {
            addWord(trieRoot, word);
        }
        
        String[] tokens = sentence.split(" ");
        
        for (int i = 0; i < tokens.length; ++i) {
            String root = search(trieRoot, tokens[i]);
            if (root != null) {
                tokens[i] = root;
            }
        }
        
        StringBuilder sb = new StringBuilder();
        for (String token : tokens) {
            if (sb.length() > 0) {
                sb.append(" ");
            }
            sb.append(token);
        }
        
        return sb.toString();
    }
    
    public String search(Trie root, String word) {
        for (int i = 0; i < word.length() 
             && (root != null && root.word == null); ++i) {
            root = root.children[word.charAt(i) - 'a'];
        }
        
        return root != null ? root.word : null;
    }
    
    public void addWord(Trie curr, String word) {
        for (int i = 0; i < word.length(); ++i) {
            int j = word.charAt(i) - 'a';

            if (curr.children[j] == null) {
                curr.children[j] = new Trie();
            }

            curr = curr.children[j];
        }

        curr.word = word;
    }
    
    
    
    class Trie {
        Trie[] children;
        String word;
        
        public Trie() {
            children = new Trie[26];
        }
    }
}

你可能感兴趣的:(648. Replace Words)