Trie前缀树-算法题

裸前缀树

题意:实现一个前缀树类,需要提供四个接口

  • Trie():初始化对象
  • void insert(String word):数据插入
  • boolean search(String word):查询字符串是否存在
  • boolean startsWith(String prefix):查询前缀是否满足

传送门

输入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
输出
[null, null, true, false, true, null, true]

解释
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

题解:通过26叉树实现

class Trie {
private:
    vector<Trie*> children;
    bool isEnd;

    Trie* searchPrefix(string prefix) {
        Trie* node = this;
        for (char ch : prefix) {
            ch -= 'a';
            if (!node->children[ch])
                return nullptr;
            node = node->children[ch];
        }
        return node;
    }

public:
    Trie() : children(26), isEnd(false) {}

    void insert(string word) {
        Trie* node = this;
        for (char ch : word) {
            ch -= 'a';
            if (!node->children[ch])
                node->children[ch] = new Trie();
            node = node->children[ch];
        }
        node->isEnd = true;
    }

    bool search(string word) {
        Trie* node = this->searchPrefix(word);
        if (node && node->isEnd) return true;
        return false;
    }

    bool startsWith(string prefix) {
        Trie* node = this->searchPrefix(prefix);
        if (node) return true;
        return false;
    }
};

前缀树+DFS

题意:给出若干字符串,找出其中所有连接词(由2个及以上的字符串组合而成);

传送门

输入:words = [“cat”,“cats”,“catsdogcats”,“dog”,“dogcatsdog”,“hippopotamuses”,“rat”,“ratcatdogcat”]
输出:[“catsdogcats”,“dogcatsdog”,“ratcatdogcat”]
解释:“catsdogcats” 由 “cats”, “dog” 和 “cats” 组成;
“dogcatsdog” 由 “dog”, “cats” 和 “dog” 组成;
“ratcatdogcat” 由 “rat”, “cat”, “dog” 和 “cat” 组成。

题解:

struct Trie {
    bool isEnd;
    vector<Trie*> children;
    Trie() {
        children = vector<Trie*>(26);
        isEnd = false;
    }
};

class Solution {
public:
    Trie *trie = new Trie();

    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        vector<string> ret;
        sort(words.begin(), words.end(), [&](const string & a, const string & b){
            return a.length() < b.length(); 
        });
        for (string &word : words) {
            if (word.empty())
                continue;
            if (dfs(word, 0))
                ret.push_back(word);
            else insert(word);
        }
        return ret;
    }

    bool dfs(const string &word, int start) {
        if (word.length() == start)
            return true;
        Trie *node = trie;
        for (int i = start; i < word.size(); i++) {
            int index = word[i] - 'a';
            node = node->children[index];
            if (!node)
                return false;
            if (node->isEnd) {
                if (dfs(word, i + 1))
                    return true;
            }
        }
        return false;
    }

    void insert(const string & word) {
        Trie *node = trie;
        for (int i = 0; i < word.size(); i++) {
            int index = word[i] - 'a';
            if (!node->children[index])
                node->children[index] = new Trie();
            node = node->children[index];
        }
        node->isEnd = true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值