Title Description (simple difficulty)
C ++ code 1
class Trie {
private:
//每个Trie节点有一个isEnd变量, 一个包含26个指针的next数组
Trie *next[26] = {nullptr};
bool isEnd = false;
public:
Trie() {
}
void insert(const string &word) { // 插入单词
Trie *root = this;
for (const auto &ch : word) {
char w = ch - 'a';
if (root->next[w] == nullptr) root->next[w] = new Trie();
root = root->next[w];
}
root->isEnd = true;
}
bool search(const string &word) { // 查找单词
Trie *root = this;
for (const auto &ch : word) {
char w = ch - 'a';
if (root->next[w] == nullptr) return false;
root = root->next[w];
}
return root->isEnd;
}
};
class Solution {
public:
string Max(string str1, string str2) {
int n1 = str1.size(), n2 = str2.size();
if (n1 > n2) return str1;
else if (n1 < n2) return str2;
else return min(str1, str2);
}
string longestWord(vector<string>& words) {
// 1.把每个单词加入到trie树中
// 2.遍历每个单词,只有当这个单词的每个字符的isEnd都是true时,才去统计res
Trie trie;
for (auto word : words) trie.insert(word);
string res = "";
for (auto word : words) {
int i;
for (i = 0; i < word.size(); i ++) {
if (trie.search(word.substr(0, i + 1))) continue;
else break;
}
if (i == word.size()) {
res = Max(res, word);
}
}
return res;
}
};
C ++ code 2
class Trie {
public:
//每个Trie节点有一个isEnd变量, 一个包含26个指针的next数组
bool isEnd;
vector<Trie*> next;
Trie() : isEnd(false), next(26) {
}
void insert(const string &word) { // 插入单词
Trie *root = this;
for (const auto &ch : word) {
char w = ch - 'a';
if (root->next[w] == nullptr) root->next[w] = new Trie();
root = root->next[w];
}
root->isEnd = true;
}
bool search(const string &word) { // 查找单词
Trie *root = this;
for (const auto &ch : word) {
char w = ch - 'a';
// 直接判断每个字符是否是前缀
if (root->next[w]->isEnd == false ) return false;
root = root->next[w];
}
return root->isEnd;
}
};
class Solution {
public:
string Max(string str1, string str2) {
int n1 = str1.size(), n2 = str2.size();
if (n1 > n2) return str1;
else if (n1 < n2) return str2;
else return min(str1, str2);
}
string longestWord(vector<string>& words) {
// 1.把每个单词加入到trie树中
// 2.遍历每个单词,而此时检索一定不会出现空指针,修改search函数,去判断isEnd即可
Trie trie;
for (auto word : words) trie.insert(word);
string res = "";
for (auto word : words) {
if (trie.search(word)) res = Max(res, word);
}
return res;
}
};
Written in the last : my blog mainly on the field of computer science summarized knowledge of thinking, and review, to write each blog it is easy to understand my goal, sharing technology and knowledge is a pleasure , and I welcome everyone together with the exchange of learning, there can be no question in the comments area, but also look forward to in-depth exchanges with your (^ ∀ ^ ●)