LeetCode(211 & 648):添加與搜索單詞 Add and Search Word & 單詞替換 Replace Words(Java)

LeetCode 從零單刷個人筆記整理(持續更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

兩道經典的手撕字典樹。用字典樹結點值end代表是否是一個字典詞的結尾,根據需求返回對應結果即可。


傳送門:添加與搜索單詞 - 數據結構設計

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.

設計一個支持以下兩種操作的數據結構:

void addWord(word)

bool search(word)

search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

說明:
你可以假設所有單詞都是由小寫字母 a-z 組成的。


/**
 *
 * 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.
 * 設計一個支持以下兩種操作的數據結構:
 * void addWord(word)
 * bool search(word)
 * search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。
 *
 */

public class AddAndSearchWord {
    class WordDictionary {

        private Trie trie;

        /** Initialize your data structure here. */
        public WordDictionary() {
            trie = new Trie();
        }

        /** Adds a word into the data structure. */
        public void addWord(String word) {
            trie.insert(word);
        }

        /** 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 trie.prefix(word);
        }

        private class Trie{
            TrieNode root;
            public Trie(){
                root = new TrieNode();
            }

            public void insert(String word){
                TrieNode node = root;
                for(char c : word.toCharArray()){
                    int idx = c - 'a';
                    if(node.children[idx] == null){
                        node.children[idx] = new TrieNode();
                    }
                    node = node.children[idx];
                }
                node.end = true;
            }

            public boolean prefix(String word){
                return prefix(word, 0, root);
            }

            public boolean prefix(String word, int curIdx, TrieNode curNode){
                TrieNode node = curNode;
                char[] chars = word.toCharArray();
                for(int i = curIdx; i < chars.length; i++){
                    if(chars[i] == '.'){
                        for(TrieNode next : node.children){
                            if(next != null && prefix(word, i + 1, next)){
                                return true;
                            }
                        }
                        return false;
                    }
                    int idx = chars[i] - 'a';
                    if(node.children[idx] == null){
                        return false;
                    }
                    node = node.children[idx];
                }
                return node.end;
            }
        }

        private class TrieNode{
            TrieNode[] children = new TrieNode[26];
            boolean end = false;
        }
    }

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




傳送門:單詞替換

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.

在英語中,我們有一個叫做 詞根(root)的概念,它可以跟着其他一些詞組成另一個較長的單詞——我們稱這個詞爲 繼承詞(successor)。例如,詞根an,跟隨着單詞 other(其他),可以形成新的單詞 another(另一個)。

現在,給定一個由許多詞根組成的詞典和一個句子。你需要將句子中的所有繼承詞用詞根替換掉。如果繼承詞有許多可以形成它的詞根,則用最短的詞根替換它。

你需要輸出替換之後的句子。

示例 1:
輸入: dict(詞典) = ["cat", "bat", "rat"]
sentence(句子) = "the cattle was rattled by the battery"
輸出: "the cat was rat by the bat"

注:
輸入只包含小寫字母。
1 <= 字典單詞數 <=1000
1 <=  句中詞語數 <= 1000
1 <= 詞根長度 <= 100
1 <= 句中詞語長度 <= 1000


import java.util.List;

/**
 *
 * 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.
 * 在英語中,我們有一個叫做 詞根(root)的概念,它可以跟着其他一些詞組成另一個較長的單詞——我們稱這個詞爲 繼承詞(successor)。
 * 例如,詞根an,跟隨着單詞 other(其他),可以形成新的單詞 another(另一個)。
 * 現在,給定一個由許多詞根組成的詞典和一個句子。你需要將句子中的所有繼承詞用詞根替換掉。如果繼承詞有許多可以形成它的詞根,則用最短的詞根替換它。
 * 你需要輸出替換之後的句子。
 *
 */

public class ReplaceWords {
    private class Trie{
        TrieNode root;
        public Trie(){
            root = new TrieNode();
        }
        public void insert(String word){
            TrieNode node = root;
            for(char c : word.toCharArray()){
                int idx = c - 'a';
                if(node.children[idx] == null){
                    node.children[idx] = new TrieNode();
                }
                node = node.children[idx];
            }
            node.end = true;
        }
        public int prefix(String word){
            TrieNode node = root;
            char[] chars = word.toCharArray();
            for(int i = 0; i < chars.length; i++){
                int idx = chars[i] - 'a';
                if(node.children[idx] == null){
                    return node.end ? i : -1;
                }
                if(node.end){
                    return i;
                }
                node = node.children[idx];
            }
            return -1;
        }
    }

    private class TrieNode{
        TrieNode[] children = new TrieNode[26];
        boolean end = false;
    }

    public String replaceWords(List<String> dict, String sentence) {
        Trie trie = new Trie();
        for(String word : dict){
            trie.insert(word);
        }
        String[] strs = sentence.split(" ");
        StringBuilder result = new StringBuilder();
        for(int i = 0; i < strs.length; i++){
            int idx = trie.prefix(strs[i]);
            if(i != 0){
                result.append(" ");
            }
            result.append(idx == -1 ? strs[i] : strs[i].substring(0, idx));
        }
        return result.toString();
    }
}




#Coding一小時,Copying一秒鐘。留個言點個讚唄,謝謝你#

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章