每日两题 / 207. 课程表 && 208. 实现 Trie (前缀树)(LeetCode热题100)

207. 课程表 - 力扣(LeetCode)
image.png

有向图判环,使用拓扑排序即可

class Solution {
public:
    #define N 2010
    vector<int> g[N];
    int in[N];
    bool st[N];
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        int n = numCourses;
        for (auto t : prerequisites) {
            int y = t[0], x = t[1];
            g[x].push_back(y);
            in[y] ++ ;
        }
        queue<int> q;
        int cnt = n;
        for (int i = 0; i < n; ++ i) {
            if (in[i] == 0) q.push(i);
        }
        while (q.size()) {
            int x = q.front(); q.pop();
            cnt -- ;
            st[x] = true;
            for (auto y : g[x]) {
                if (!st[y] && -- in[y] == 0) q.push(y);
            }
        }
        return cnt == 0;
    }
};

208. 实现 Trie (前缀树) - 力扣(LeetCode)
image.png
关于Trie树

class Trie {
public:
    #define N 100010
    int son[N][26], cnt[N], idx;
    Trie() {
        memset(son, 0, sizeof son);
        memset(cnt, 0, sizeof cnt);
        idx = 0;
    }
    
    void insert(string word) {
        int p = 0;
        for (auto t : word) {
            t -= 'a';
            if (!son[p][t]) son[p][t] = ++ idx ;
            p = son[p][t];
        }
        cnt[p] ++ ;
    }
    
    bool search(string word) {
        int p = 0;
        for (auto t : word) {
            t -= 'a';
            if (!son[p][t]) return false;
            p = son[p][t];
        }
        if (cnt[p]) return true;
        return false;
    }
    
    bool startsWith(string prefix) {
        int p = 0;
        for (auto t : prefix) {
            t -= 'a';
            if (!son[p][t]) return false;
            p = son[p][t];
        }
        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);
 */
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值