Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
longest-word-in-dictionary.cpp 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-11-06 00:30 +08:00 . Update longest-word-in-dictionary.cpp
// Time: O(n), n is the total sum of the lengths of words
// Space: O(t), t is the number of nodes in trie
class Solution {
public:
string longestWord(vector<string>& words) {
TrieNode trie;
for (int i = 0; i < words.size(); ++i) {
trie.Insert(words[i], i);
}
// DFS
stack<TrieNode *> stk;
for (const auto& node : trie.leaves) {
if (node) {
stk.emplace(node);
}
}
string result;
while (!stk.empty()) {
const auto curr = stk.top(); stk.pop();
if (curr->isString) {
const auto& word = words[curr->val];
if (word.size() > result.size() || (word.size() == result.size() && word < result)) {
result = word;
}
for (const auto& node : curr->leaves) {
if (node) {
stk.emplace(node);
}
}
}
}
return result;
}
private:
struct TrieNode {
bool isString;
int val;
vector<TrieNode *> leaves;
TrieNode() : isString{false}, val{0}, leaves(26) {}
void Insert(const string& s, const int i) {
auto* p = this;
for (const auto& c : s) {
if (!p->leaves[c - 'a']) {
p->leaves[c - 'a'] = new TrieNode;
}
p = p->leaves[c - 'a'];
}
p->isString = true;
p->val = i;
}
~TrieNode() {
for (auto& node : leaves) {
if (node) {
delete node;
}
}
}
};
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助