前缀树 leecode相关题集练习(二)

212. 单词搜索 II

给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

示例:
输入:
words = [“oath”,“pea”,“eat”,“rain”] and board =
[
[‘o’,‘a’,‘a’,‘n’],
[‘e’,‘t’,‘a’,‘e’],
[‘i’,‘h’,‘k’,‘r’],
[‘i’,‘f’,‘l’,‘v’]
]
输出: [“eat”,“oath”]

class Trie{
private:
    bool isEnd;
    Trie *next[26];
    string str;

public:
    Trie(){
        isEnd=false;
        str="";
        memset(next, NULL, sizeof(next));
    }
    void insert(string word)//插入单词,建立前缀树
    {
        Trie *root=this;
        for(auto w:word)
        {
            if(root->next[w-'a']==nullptr)root->next[w-'a']=new Trie();
            root=root->next[w-'a'];
        }
        root->isEnd=true;
        root->str= word; //这个地址为结尾的这个单词赋值给str
        //cout << "str:" << root->str << endl;
    }
    void search(vector<string>& result,vector<vector<char>>& board)
    {
        Trie *root=this;
        for(int i = 0;i < board.size();++i)//每一个坐标都要开始dfs
            for(int j = 0;j < board[0].size(); ++j)
                dfs(result,board,root,i,j);
    }

    void dfs(vector<string>& result,vector<vector<char>>& board,Trie* node,int x,int y)
    {
        if(node->isEnd==true){//在board中找到words中一个单词,添加到result中
            node->isEnd=false;//将该单词标记为false,防止在word中再次递归到这个单词,从而造成重复添加
            result.push_back(node->str);
            return;
        }
        if(x<0||x==board.size()||y<0||y==board[x].size())return;//超出边界,不能继续递归
        if(board[x][y]=='#'||node->next[board[x][y]-'a']==nullptr)return;//坐标(x,y)对应的字符不在前缀树中,递归方向不对,返回到上一个坐标
        node=node->next[board[x][y]-'a'];//node指向下一个字符节点
        char temp=board[x][y];
        board[x][y]='#';//标记(x,y)对应的字符已被访问过,防止同一个单元格内的字符在一个单词中重复使用
        dfs(result,board,node,x+1,y);
        dfs(result,board,node,x-1,y);
        dfs(result,board,node,x,y+1);
        dfs(result,board,node,x,y-1);
        board[x][y]=temp;
    }
};
class Solution {
public: 
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        Trie *root=new Trie();
        vector<string> result;
        for(auto word:words)
            root->insert(word);
        root->search(result,board);
        return result;       
    }
};

472. 连接词

给定一个不含重复单词的列表,编写一个程序,返回给定单词列表中所有的连接词。

连接词的定义为:一个字符串完全是由至少两个给定数组中的单词组成的。

示例:
输入: [“cat”,“cats”,“catsdogcats”,“dog”,“dogcatsdog”,“hippopotamuses”,“rat”,“ratcatdogcat”]

输出: [“catsdogcats”,“dogcatsdog”,“ratcatdogcat”]

解释: “catsdogcats"由"cats”, “dog” 和 "cats"组成;
“dogcatsdog"由"dog”, "cats"和"dog"组成;
“ratcatdogcat"由"rat”, “cat”, "dog"和"cat"组成。
说明:
给定数组的元素总数不超过 10000。
给定数组中元素的长度总和不超过 600000。
所有输入字符串只包含小写字母。
不需要考虑答案输出的顺序。


题解:
主要利用前缀树解题,先建树,然后进行搜索操作。
这里简单讲解一下搜索单词,例如寻找catsdogcats,当i为2时,我们在前缀树发现cat是一个子单词,然后开始search(sdogcats),然而发现这个并不是子单词,那就证明以cat作为分界词就错了。我们继续for循环,然后匹配到cats时,在递归匹配dogcats,直到for循环结束!

class Solution {
private:
    struct Trie {
        bool is_string;
        Trie *next[26]{nullptr};
        Trie() : is_string(false) {}
    };
    Trie* root;

public: 
    void insert(const vector<string>& words){
        //  Trie *root = new Trie();
        root = new Trie;
        for(const auto &word:words){
            auto node = root;
            for(const auto& w:word){
                if(node->next[w-'a']==nullptr) node->next[w-'a']=new Trie();
                node = node->next[w-'a'];
            }
            node-> is_string= true;
        }       
    }
    bool search(string word,int index,int count){
        Trie *node = root;//每次从根节点开始搜索
        for(int i=index; i < word.size(); ++i){
            //word的某个字符不在前缀树中
            if(node->next[word[i]-'a']== nullptr) return false;
            node=node->next[word[i]-'a'];
            //到达某个单词尾
            if(node->is_string){
                
                if(i == word.size()-1)
                //count的数量至少为2个,若遍历到最后只有一个单词,则count的值还是为0
                    return count >= 1;
                //已前count位的单词作为分解词继续匹配下一个单词,下个单词满足count才能返回ture,否则继续寻找下一个分界单词
                if(search(word,i+1,count+1)) return true;
            }
        }
        return false;
    }
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {   
        insert(words);
        vector<string> res;
        for (auto& w : words) {
            if (search(w, 0, 0)) {
                res.push_back(w);
            }
        }
        return res;
    }
};

421. 数组中两个数的最大异或值

给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 。

找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ≤ i, j < n 。

你能在O(n)的时间解决这个问题吗?

示例:

输入: [3, 10, 5, 25, 2, 8]

输出: 28

解释: 最大的结果是 5 ^ 25 = 28.

题解:

主要思路就是把nums里的每个数建树,一共有31位,如果当前位上是0,就往左子树走,如果当前位是1,就往右子树走,走完了就记录一下这条路径上的这个数是多少。

然后再线性扫描数组,用贪心的策略向下遍历树,贪心的地方在于,如果当前位上是0,而有右子树,就往右子树走,因为这样0和右子树上的1异或可以得到1,反之就往左子树走。
这种贪心策略的正确性在于,优先保障高位异或得到1。而对于二进制的数来说,为了得到更大的异或值,最高位的1的重要性比其他位1更高,比如 1000一定大于0111,所以得到的一定会是最大的异或值。
总的来说就只需要两步:
将数组中的数全部存入字典树中
遍历树中的每一个数在字典树中异或的最大结果,最后再求最大结果里面的最大值返回就是了
也可以将1、2两步写在一个循环里面

class Solution {
public:
    struct Trie{
        Trie* next[2]{NULL};
    };
    // Trie* root;

    int findMaximumXOR(vector<int>& nums) {
        Trie* root = new Trie();
        //将数按照二进制形式全部存入字典树里面 insert 函数
        for(int num : nums){
            Trie* node = root;
            for(int i = 31; i >= 0; i--){
                int bt = num >> i&1;  //(这里优先级是先进行 >> 然后进行 &)
                if(node ->next[bt] == NULL) node ->next[bt] = new Trie();
                node = node ->next[bt];
            }
        }
        
        int res = 0,temp = 0;
        Trie* note = root;
        for(auto num : nums){
            note = root; temp = 0;
            for(int i = 31; i >= 0; --i){
                int t = num >> i & 1;
                if(note -> next[!t]){
                    note = note ->next[!t];
                    temp += (1 << i);
                }
                else
                    note = note->next[t];
            }
            res = max(res, temp);
        }
        return res;  
    }
};

676. 实现一个魔法字典
实现一个带有buildDict, 以及 search方法的魔法字典。

对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。

对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

示例 1:

Input: buildDict([“hello”, “leetcode”]), Output: Null
Input: search(“hello”), Output: False
Input: search(“hhllo”), Output: True
Input: search(“hell”), Output: False
Input: search(“leetcoded”), Output: False
注意:

你可以假设所有输入都是小写字母 a-z。
为了便于竞赛,测试所用的数据量很小。你可以在竞赛结束后,考虑更高效的算法。
请记住重置MagicDictionary类中声明的类变量,因为静态/类变量会在多个测试用例中保留。 请参阅这里了解更多详情。

题解:前缀树+DFS
相关题型有:
leetcode211:添加与搜索单词——数据结构设计(medium)
leetcode212:单词搜索 Ⅱ(hard)

代码如下:

class MagicDictionary {
public:
    struct Trie{
        bool isEnd = false;
        Trie *next[26] = {NULL};
    };
    Trie* root;
    /** Initialize your data structure here. */
    MagicDictionary() {
        root = new Trie();
    }
    
    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for(const auto& word:dict){
            Trie* node = root;
            for(const auto& w : word){
                if(node ->next[w - 'a'] == NULL) node->next[w-'a'] = new Trie();
                node = node ->next[w-'a'];
            }
            node -> isEnd = true;
        }
    }
    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    bool search(string word) {
        return dfs(word,root, 0,false);
    }
    bool dfs(string word, Trie* node, int idx, bool isMod){
        if(node == NULL) return false;
        if(word.size() == idx) return isMod && node ->isEnd; //同时满足更改了一次,也到了单词的结尾
        for(int i = 0; i < 26; ++i){
           if(node -> next[i] != NULL){
               if(word[idx] == i + 'a'){
                   //找到的节点字符与index对应的字符相等,继续匹配下一个字符
                   if(dfs(word, node->next[i], idx + 1,isMod))
                        return true;
               }
               //如果'a'+i!=word[index],则使用替换字母的机会(在此之前替换字母的机会是没有使用的,因为只能使用一次)
               else if(isMod == false && dfs(word,node->next[i], idx+1, true))
                    return true;
           } 
        }
        return false;
    }
};

/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary* obj = new MagicDictionary();
 * obj->buildDict(dict);
 * bool param_2 = obj->search(word);
 */

677. 键值映射
实现一个 MapSum 类里的两个方法,insert 和 sum。

对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。

对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。

示例 1:

输入: insert(“apple”, 3), 输出: Null
输入: sum(“ap”), 输出: 3
输入: insert(“app”, 2), 输出: Null
输入: sum(“ap”), 输出: 5

本题采用前缀树来解题,前缀树节点设有三个成员变量,sumval用来存储字符串前缀的val(前缀就是除去尾字符之前的字符叫前缀)以及相同的key要更新前缀的val,字符串尾字符的val就是记录字符串的val,next[26]表示每个节点值可以取到26个小写字母中的一个。这里我们用一个haspmap来记录遇到相同的key时,原来的val将被替代。
代码如下:

class MapSum {

public:
    struct Trie{
        int val,sumval;
        Trie *next[26]{NULL};
        Trie():val(0),sumval(0){};
    };
private:
    Trie *root;
    unordered_map<string,int>record;

public:
    
    /** Initialize your data structure here. */
    MapSum() {
        root = new Trie();
        record.clear();
    }
    void insert(string key, int val) {
        Trie* note = root;
        int size = key.size();
        for(int i = 0; i < size; i++){
            if(note->next[key[i] - 'a'] == NULL)
                note -> next[key[i] - 'a'] = new Trie();
            if(i != size-1)
                (note->next[key[i] - 'a'])->sumval += val-record[key];
            note = note->next[key[i] - 'a'];
        }
        record[key] = val;
        note -> val = val;
    }
    int sum(string prefix) {
        Trie* node = root;
        for(auto p : prefix){
            if(node -> next[p-'a'] == NULL)
                return 0;
            node = node ->next[p - 'a'];
        }
        return node->val + node->sumval;
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum* obj = new MapSum();
 * obj->insert(key,val);
 * int param_2 = obj->sum(prefix);
 */

720. 词典中最长的单词

给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

若无答案,则返回空字符串。

示例 1:

输入:
words = [“w”,“wo”,“wor”,“worl”, “world”]
输出: “world”
解释:
单词"world"可由"w", “wo”, “wor”, 和 "worl"添加一个字母组成。
示例 2:

输入:
words = [“a”, “banana”, “app”, “appl”, “ap”, “apply”, “apple”]
输出: “apple”
解释:
“apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply”。

class Trie{
private:
    bool isEnd;
    Trie *next[26];
public:

    Trie(){
        isEnd = false;
        memset(next, 0, sizeof(next));
    }
    void insert(string word){
        Trie* root = this;
        for(const auto& w:word){
            if(root -> next[w-'a'] == nullptr) root->next[w-'a'] = new Trie();
            root = root->next[w- 'a'];
        }
        root ->isEnd = true;
    }
    bool search(string word){
        Trie* root = this;
        for(const auto& w:word){
            if(root -> next[w-'a'] == nullptr || root ->next[w-'a'] -> isEnd == false)
                return false;
            root = root->next[w-'a'];
        }
        return true;
    }
};
//首先分析一下题意:从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。
//这句话的意思是说,最长单词的每个字符在前缀中对应的节点都能表示一个字符串,
//还有一点需要注意的是在最长单词相等时,我们需要选择字典序小的单词,明白这两点,接下来解题就是套用前缀树模板了。
//然后就是两次遍历字符串数组,第一次遍历是建立前缀树,第二次遍历是寻找最长单词了。
class Solution {
public:
    string longestWord(vector<string>& words) {
        if(words.size() == 0) return "";
        Trie* root = new Trie();
        for(auto word:words)
            root->insert(word);

        string res = "";
        for(auto word : words){
            if(root -> search(word)){
                if(word.size() > res.size())
                    res = word;
                else if(word.size() == res.size() && word < res)
                    res = word;
            }
        }
        return res;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值