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一秒钟。留个言点个赞呗,谢谢你#

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