LeetCode算法练习——字典树(一)

本文介绍了字典树(Trie树)的数据结构及其在LeetCode题目中的应用,包括实现Trie的基本操作以及如何用Trie优化单词搜索问题。文章通过解析LeetCode208和212题目的解决方案,阐述了字典树如何提高查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字典树

       又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

字典树的性质:

  • 根节点不包含字符,除根节点外每一个节点都只包含一个字符
  • 从根节点到某一个节点,路径上经过的字符连接起来,就是该节点对应的字符串
  • 每个节点的所有子节点包含的字符都不相同。

LeetCode208. 实现 Trie (前缀树)

实现一个 Trie (前缀树),包含 insertsearch, 和 startsWith 这三个操作。

示例
Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // 返回 true
trie.search("app");     // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");   
trie.search("app");     // 返回 true

此题的目的就是了解字典树的基本操作,完整代码如下:

class Trie{
public:
	struct Node{
    	bool isWord = false;
    	string word; // 加入存储单词节点
    	Node* next[26];
	};
    Node* root;
    Trie(){
        this->root = new Node();
    }
    //插入
    void insert(string word){
        Node* prefix = root;
        for(int i = 0; i < word.size(); i++){
            if(prefix->next[word[i] - 'a'] == nullptr)
                prefix->next[word[i] - 'a'] = new Node();
            prefix = prefix->next[word[i] - 'a'];
        }
        if(!prefix->isWord){
            prefix->isWord = true;
            prefix->word = word;
        }
    }
    //搜索
    bool search(string word){
        Node* prefix = root;
        for(char ch : word){
            if(prefix->next[ch - 'a'] == nullptr)
                return false;
            prefix = prefix->next[ch - 'a'];
        }
        return prefix->isWord;
    }
    //前缀是否匹配
    bool startsWith(string word){
	Node* prefix = root;
	for(char ch : word){
            if(prefix->next[ch - 'a'] == nullptr)
                return false;
            prefix = prefix->next[ch - 'a'];
        }
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

LeetCode212.  单词搜索2

给定一个二维网格 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"]

此题的核心是用回溯思想做,但是如果在LeetCode79-单词搜索1的基础上加一个循环,暴力解决的话,会出现超时,因此需要对算法的时间复杂度进行优化,于是我们引入了字典树的来优化单词存储遍历的方式,套用LeetCode-208的字典树模板代码完成,完整代码如下:

class Trie{
public:
	struct Node{
    	bool isWord = false;
    	string word; // 加入存储单词节点
    	Node* next[26];
	};
    Node* root;
    Trie(){
        this->root = new Node();
    }
    void insert(string& word){
        Node* prefix = root;
        for(int i = 0; i < word.size(); i++){
            if(prefix->next[word[i] - 'a'] == nullptr)
                prefix->next[word[i] - 'a'] = new Node();
            prefix = prefix->next[word[i] - 'a'];
        }
        if(!prefix->isWord){
            prefix->isWord = true;
            prefix->word = word;
        }
    }
};

class Solution {
private:
    int row, column;
    vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    vector<vector<bool>> visited;
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        // DFS+Trie优化
        vector<string> res;
        row = board.size();
        if(row == 0)
            return res;
        column = board[0].size();
        if(column == 0)
            return res;
        Trie* T = new Trie();
        for(string &word: words){
            T->insert(word);
        }
        visited = vector<vector<bool>>(row, vector<bool>(column, false));
        // DFS
        for(int i = 0; i < row; ++i){
            for(int j = 0; j < column; ++j){
                Trie::Node* prefix = T->root;
                if(prefix->next[board[i][j]-'a'] != nullptr)
                    dfs(board, i, j, prefix->next[board[i][j]-'a'], res);
            }
        }
        return res;
    }

private:
    void dfs(const vector<vector<char>>& board, int i, int j, Trie::Node* prefix, vector<string>& res){
        if(prefix->isWord){
            if(count(res.begin(), res.end(), prefix->word)==0)
                res.push_back(prefix->word);
        }
        visited[i][j] = true;
        for(auto &d: dirs){
            int x = i + d[0];
            int y = j + d[1];
            if((0 <= x && x < row && 0 <= y && y < column) && !visited[x][y] && prefix->next[board[x][y] - 'a']!=nullptr){
                dfs(board, x, y, prefix->next[board[x][y] - 'a'], res);
            }
        }
        visited[i][j] = false;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值