Skip to content

[pull] main from doocs:main #375

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 20, 2025
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
391 changes: 287 additions & 104 deletions solution/0700-0799/0720.Longest Word in Dictionary/README.md

Large diffs are not rendered by default.

385 changes: 289 additions & 96 deletions solution/0700-0799/0720.Longest Word in Dictionary/README_EN.md

Large diffs are not rendered by default.

57 changes: 39 additions & 18 deletions solution/0700-0799/0720.Longest Word in Dictionary/Solution.cpp
Original file line number Diff line number Diff line change
@@ -1,26 +1,47 @@
class Solution {
class Trie {
public:
string longestWord(vector<string>& words) {
unordered_set<string> s(words.begin(), words.end());
int cnt = 0;
string ans = "";
for (auto w : s) {
int n = w.size();
if (check(w, s)) {
if (cnt < n) {
cnt = n;
ans = w;
} else if (cnt == n && w < ans)
ans = w;
Trie* children[26] = {nullptr};
bool isEnd = false;

void insert(const string& w) {
Trie* node = this;
for (char c : w) {
int idx = c - 'a';
if (node->children[idx] == nullptr) {
node->children[idx] = new Trie();
}
node = node->children[idx];
}
return ans;
node->isEnd = true;
}

bool check(string& word, unordered_set<string>& s) {
for (int i = 1, n = word.size(); i < n; ++i)
if (!s.count(word.substr(0, i)))
bool search(const string& w) {
Trie* node = this;
for (char c : w) {
int idx = c - 'a';
if (node->children[idx] == nullptr || !node->children[idx]->isEnd) {
return false;
}
node = node->children[idx];
}
return true;
}
};
};

class Solution {
public:
string longestWord(vector<string>& words) {
Trie trie;
for (const string& w : words) {
trie.insert(w);
}

string ans = "";
for (const string& w : words) {
if (trie.search(w) && (ans.length() < w.length() || (ans.length() == w.length() && w < ans))) {
ans = w;
}
}
return ans;
}
};
56 changes: 36 additions & 20 deletions solution/0700-0799/0720.Longest Word in Dictionary/Solution.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,43 @@
type Trie struct {
children [26]*Trie
isEnd bool
}

func (t *Trie) insert(w string) {
node := t
for i := 0; i < len(w); i++ {
idx := w[i] - 'a'
if node.children[idx] == nil {
node.children[idx] = &Trie{}
}
node = node.children[idx]
}
node.isEnd = true
}

func (t *Trie) search(w string) bool {
node := t
for i := 0; i < len(w); i++ {
idx := w[i] - 'a'
if node.children[idx] == nil || !node.children[idx].isEnd {
return false
}
node = node.children[idx]
}
return true
}

func longestWord(words []string) string {
s := make(map[string]bool)
trie := &Trie{}
for _, w := range words {
s[w] = true
trie.insert(w)
}
cnt := 0

ans := ""
check := func(word string) bool {
for i, n := 1, len(word); i < n; i++ {
if !s[word[:i]] {
return false
}
}
return true
}
for w, _ := range s {
n := len(w)
if check(w) {
if cnt < n {
cnt, ans = n, w
} else if cnt == n && w < ans {
ans = w
}
for _, w := range words {
if trie.search(w) && (len(ans) < len(w) || (len(ans) == len(w) && w < ans)) {
ans = w
}
}
return ans
}
}
56 changes: 36 additions & 20 deletions solution/0700-0799/0720.Longest Word in Dictionary/Solution.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,46 @@
class Solution {
private Set<String> s;
class Trie {
private Trie[] children = new Trie[26];
private boolean isEnd = false;

public String longestWord(String[] words) {
s = new HashSet<>(Arrays.asList(words));
int cnt = 0;
String ans = "";
for (String w : s) {
int n = w.length();
if (check(w)) {
if (cnt < n) {
cnt = n;
ans = w;
} else if (cnt == n && w.compareTo(ans) < 0) {
ans = w;
}
public void insert(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
return ans;
node.isEnd = true;
}

private boolean check(String word) {
for (int i = 1, n = word.length(); i < n; ++i) {
if (!s.contains(word.substring(0, i))) {
public boolean search(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null || !node.children[idx].isEnd) {
return false;
}
node = node.children[idx];
}
return true;
}
}
}

class Solution {
public String longestWord(String[] words) {
Trie trie = new Trie();
for (String w : words) {
trie.insert(w);
}
String ans = "";
for (String w : words) {
if (trie.search(w)
&& (ans.length() < w.length()
|| (ans.length() == w.length() && w.compareTo(ans) < 0))) {
ans = w;
}
}
return ans;
}
}
49 changes: 49 additions & 0 deletions solution/0700-0799/0720.Longest Word in Dictionary/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @param {string[]} words
* @return {string}
*/
var longestWord = function (words) {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}

let ans = '';
for (const w of words) {
if (trie.search(w) && (ans.length < w.length || (ans.length === w.length && w < ans))) {
ans = w;
}
}
return ans;
};

class Trie {
constructor() {
this.children = Array(26).fill(null);
this.isEnd = false;
}

insert(w) {
let node = this;
for (let i = 0; i < w.length; i++) {
const idx = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
node.isEnd = true;
}

search(w) {
let node = this;
for (let i = 0; i < w.length; i++) {
const idx = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null || !node.children[idx].isEnd) {
return false;
}
node = node.children[idx];
}
return true;
}
}
44 changes: 35 additions & 9 deletions solution/0700-0799/0720.Longest Word in Dictionary/Solution.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,38 @@
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
self.is_end = False

def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True

def search(self, w: str) -> bool:
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
return False
node = node.children[idx]
if not node.is_end:
return False
return True


class Solution:
def longestWord(self, words: List[str]) -> str:
cnt, ans = 0, ''
s = set(words)
for w in s:
n = len(w)
if all(w[:i] in s for i in range(1, n)):
if cnt < n:
cnt, ans = n, w
elif cnt == n and w < ans:
ans = w
trie = Trie()
for w in words:
trie.insert(w)
ans = ""
for w in words:
if trie.search(w) and (
len(ans) < len(w) or (len(ans) == len(w) and ans > w)
):
ans = w
return ans
62 changes: 49 additions & 13 deletions solution/0700-0799/0720.Longest Word in Dictionary/Solution.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,54 @@
impl Solution {
pub fn longest_word(mut words: Vec<String>) -> String {
words.sort_unstable_by(|a, b| (b.len(), a).cmp(&(a.len(), b)));
for word in words.iter() {
let mut is_pass = true;
for i in 1..=word.len() {
if !words.contains(&word[..i].to_string()) {
is_pass = false;
break;
}
struct Trie {
children: [Option<Box<Trie>>; 26],
is_end: bool,
}

impl Trie {
fn new() -> Self {
Trie {
children: Default::default(),
is_end: false,
}
}

fn insert(&mut self, w: &str) {
let mut node = self;
for c in w.chars() {
let idx = (c as usize) - ('a' as usize);
if node.children[idx].is_none() {
node.children[idx] = Some(Box::new(Trie::new()));
}
node = node.children[idx].as_mut().unwrap();
}
node.is_end = true;
}

fn search(&self, w: &str) -> bool {
let mut node = self;
for c in w.chars() {
let idx = (c as usize) - ('a' as usize);
if node.children[idx].is_none() || !node.children[idx].as_ref().unwrap().is_end {
return false;
}
if is_pass {
return word.clone();
node = node.children[idx].as_ref().unwrap();
}
true
}
}

impl Solution {
pub fn longest_word(words: Vec<String>) -> String {
let mut trie = Trie::new();
for w in &words {
trie.insert(w);
}

let mut ans = String::new();
for w in words {
if trie.search(&w) && (ans.len() < w.len() || (ans.len() == w.len() && w < ans)) {
ans = w;
}
}
String::new()
ans
}
}
Loading