Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions leetcodes/720-longest-word-in-dictionary/720.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
struct TrieNode {
vector<shared_ptr<TrieNode>> children;
const string* word = nullptr;
TrieNode() : children(26) {}
};

class Solution {
public:
string longestWord(vector<string>& words) {
for (const string& word : words)
insert(word);
return longestWordFrom(root);
}

private:
shared_ptr<TrieNode> root = make_shared<TrieNode>();

void insert(const string& word) {
shared_ptr<TrieNode> node = root;
for (const char c : word) {
const int i = c - 'a';
if (node->children[i] == nullptr)
node->children[i] = make_shared<TrieNode>();
node = node->children[i];
}
node->word = &word;
}

string longestWordFrom(shared_ptr<TrieNode> node) {
string ans = node->word ? *node->word : "";

for (shared_ptr<TrieNode> child : node->children)
if (child && child->word) {
string childWord = longestWordFrom(child);
if (childWord.length() > ans.length())
ans = childWord;
}

return ans;
}
};
38 changes: 38 additions & 0 deletions leetcodes/720-longest-word-in-dictionary/720.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public String word;
}

class Solution {
public String longestWord(String[] words) {
for (final String word : words)
insert(word);
return longestWordFrom(root);
}

private TrieNode root = new TrieNode();

private void insert(final String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
final int i = c - 'a';
if (node.children[i] == null)
node.children[i] = new TrieNode();
node = node.children[i];
}
node.word = word;
}

private String longestWordFrom(TrieNode node) {
String ans = node.word == null ? "" : node.word;

for (TrieNode child : node.children)
if (child != null && child.word != null) {
String childWord = longestWordFrom(child);
if (childWord.length() > ans.length())
ans = childWord;
}

return ans;
}
}
25 changes: 25 additions & 0 deletions leetcodes/720-longest-word-in-dictionary/720.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def longestWord(self, words: list[str]) -> str:
root = {}

for word in words:
node = root
for c in word:
if c not in node:
node[c] = {}
node = node[c]
node['word'] = word

def dfs(node: dict) -> str:
ans = node['word'] if 'word' in node else ''

for child in node:
if 'word' in node[child] and len(node[child]['word']) > 0:
childWord = dfs(node[child])
if len(childWord) > len(ans) or (
len(childWord) == len(ans) and childWord < ans):
ans = childWord

return ans

return dfs(root)