「这是我参与2022首次更文挑战的第12天,活动详情查看:2022首次更文挑战」
1、题目
你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1 。
在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] ,表示如果要学习课程 ai 则 必须 先学习课程 bi 。
- 例如,先修课程对
[0, 1]表示:想要学习课程0,你需要先完成课程1。
请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false 。
示例 1:
输入:numCourses = 2, prerequisites = [[1,0]]
输出:true
解释:总共有 2 门课程。学习课程 1 之前,你需要完成课程 0 。这是可能的。
示例 2:
输入:numCourses = 2, prerequisites = [[1,0],[0,1]]
输出:false
解释:总共有 2 门课程。学习课程 1 之前,你需要先完成课程 0 ;并且学习课程 0 之前,你还应先完成课程 1 。这是不可能的。
提示:
1 <= numCourses <= 1050 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCoursesprerequisites[i]中的所有课程对 互不相同
2、思路
字典树
字典树,顾名思义,是关于“字典”的一棵树。即:它是对于字典的一种存储方式(所以是一种数据结构而不是算法)。这个词典中的每个“单词”就是从根节点出发一直到某一个目标节点的路径,路径中每条边的字母连起来就是一个单词。
标橙色的节点是“目标节点“,即根节点到这个目标节点的路径上的所有字母构成了一个单词。
作用:
- 1、维护字符串集合 (字典)
- 2、向字符串集合中插入字符串 (建树)
- 3、查询字符串集合中是否有某个字符串 (查询)
- 4、查询字符串集合中是否有某个字符串的前缀 (查询)
具体操作:
定义字典树节点
struct Node {
bool is_end; // 表示是否存在以这个点为结尾的单词
Node *son[26]; // 26个小写字母子结点
Node() { // 初始化
is_end = false;
for (int i = 0; i < 26; i ++ )
son[i] = NULL;
}
}*root;
向字典树中插入一个单词word
从根结点出发,沿着字符串的字符一直往下走,若某一字符不存在,则直接把它创建出来,继续走下去,走完了整个单词,标记最后的位置的is_end = true。
void insert(string word) {
auto p = root;
for (auto c: word) {
int u = c - 'a';
if (!p->son[u]) p->son[u] = new Node();
p = p->son[u];
}
p->is_end = true;
}
查找字典树中是否存在单词word
从根结点出发,沿着字符串的字符一直往下走,若某一字符不存在,则直接return false,当很顺利走到最后的位置的时候,判断最后一个位置的is_end即可。
bool search(string word) {
auto p = root;
for (auto c: word) {
int u = c - 'a';
if (!p->son[u]) return false;
p = p->son[u];
}
return p->is_end;
}
查找字典树中是否有以prefix为前缀的单词
从根结点出发,沿着字符串的字符一直往下走,若某一字符不存在,则直接return false,如果顺利走到最后一个位置,则返回true。
bool startsWith(string word) {
auto p = root;
for (auto c: word) {
int u = c - 'a';
if (!p->son[u]) return false;
p = p->son[u];
}
return true;
}
时间复杂度分析: O(n),n表示单词操作字符串长度。
3、c++代码
class Trie {
public:
struct Node{
bool is_end;
Node *son[26];
Node(){
is_end = false;
for(int i = 0; i < 26; i++)
son[i] = NULL;
}
}*root;
Trie() {
root = new Node();
}
void insert(string word) {
auto p = root;
for(auto c : word){
int u = c - 'a';
if(!p->son[u]) p->son[u] = new Node();
p = p->son[u];
}
p->is_end = true;
}
bool search(string word) {
auto p = root;
for(auto c : word){
int u = c - 'a';
if(!p->son[u]) return false;
p = p->son[u];
}
return p->is_end;
}
bool startsWith(string prefix) {
auto p = root;
for(auto c : prefix){
int u = c -'a';
if(!p->son[u]) return false;
p = p->son[u];
}
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);
*/