Skip to content

feat: add solutions to lcci problem: No.17.15 #4061

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 1 commit into from
Feb 14, 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
314 changes: 158 additions & 156 deletions lcci/17.15.Longest Word/README.md

Large diffs are not rendered by default.

314 changes: 158 additions & 156 deletions lcci/17.15.Longest Word/README_EN.md

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions lcci/17.15.Longest Word/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
public:
string longestWord(vector<string>& words) {
unordered_set<string> s(words.begin(), words.end());
ranges::sort(words, [&](const string& a, const string& b) {
return a.size() > b.size() || (a.size() == b.size() && a < b);
});
auto dfs = [&](this auto&& dfs, string w) -> bool {
if (w.empty()) {
return true;
}
for (int k = 1; k <= w.size(); ++k) {
if (s.contains(w.substr(0, k)) && dfs(w.substr(k))) {
return true;
}
}
return false;
};
for (const string& w : words) {
s.erase(w);
if (dfs(w)) {
return w;
}
}
return "";
}
};
56 changes: 11 additions & 45 deletions lcci/17.15.Longest Word/Solution.go
Original file line number Diff line number Diff line change
@@ -1,62 +1,28 @@
type Trie struct {
children [26]*Trie
isEnd bool
}

func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}

func (this *Trie) search(word string) bool {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return node.isEnd
}

func longestWord(words []string) string {
s := map[string]bool{}
for _, w := range words {
s[w] = true
}
sort.Slice(words, func(i, j int) bool {
a, b := words[i], words[j]
if len(a) != len(b) {
return len(a) < len(b)
}
return a > b
return len(words[i]) > len(words[j]) || (len(words[i]) == len(words[j]) && words[i] < words[j])
})
trie := newTrie()
var dfs func(string) bool
dfs = func(w string) bool {
if len(w) == 0 {
return true
}
for i := 1; i <= len(w); i++ {
if trie.search(w[:i]) && dfs(w[i:]) {
for k := 1; k <= len(w); k++ {
if s[w[:k]] && dfs(w[k:]) {
return true
}
}
return false
}
ans := ""
for _, w := range words {
s[w] = false
if dfs(w) {
ans = w
return w
}
trie.insert(w)
}
return ans
}
return ""
}
53 changes: 13 additions & 40 deletions lcci/17.15.Longest Word/Solution.java
Original file line number Diff line number Diff line change
@@ -1,61 +1,34 @@
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;

void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}

boolean search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
}

class Solution {
private Trie trie = new Trie();
private Set<String> s = new HashSet<>();

public String longestWord(String[] words) {
for (String w : words) {
s.add(w);
}
Arrays.sort(words, (a, b) -> {
if (a.length() != b.length()) {
return a.length() - b.length();
return b.length() - a.length();
}
return b.compareTo(a);
return a.compareTo(b);
});
String ans = "";
for (String w : words) {
s.remove(w);
if (dfs(w)) {
ans = w;
return w;
}
trie.insert(w);
}
return ans;
return "";
}

private boolean dfs(String w) {
if ("".equals(w)) {
if (w.length() == 0) {
return true;
}
for (int i = 1; i <= w.length(); ++i) {
if (trie.search(w.substring(0, i)) && dfs(w.substring(i))) {
for (int k = 1; k <= w.length(); ++k) {
if (s.contains(w.substring(0, k)) && dfs(w.substring(k))) {
return true;
}
}
return false;
}
}
}
51 changes: 12 additions & 39 deletions lcci/17.15.Longest Word/Solution.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,17 @@
class Trie:
def __init__(self):
self.children = [None] * 26
self.is_end = False

def insert(self, word):
node = self
for c in word:
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, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return False
node = node.children[idx]
return node.is_end


class Solution:
def longestWord(self, words: List[str]) -> str:
def cmp(a, b):
if len(a) != len(b):
return len(a) - len(b)
return -1 if a > b else 1

def dfs(w):
return not w or any(
trie.search(w[:i]) and dfs(w[i:]) for i in range(1, len(w) + 1)
)
def dfs(w: str) -> bool:
if not w:
return True
for k in range(1, len(w) + 1):
if w[:k] in s and dfs(w[k:]):
return True
return False

words.sort(key=cmp_to_key(cmp))
trie = Trie()
ans = ""
s = set(words)
words.sort(key=lambda x: (-len(x), x))
for w in words:
s.remove(w)
if dfs(w):
ans = w
trie.insert(w)
return ans
return w
return ""
28 changes: 28 additions & 0 deletions lcci/17.15.Longest Word/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::collections::HashSet;

impl Solution {
pub fn longest_word(words: Vec<String>) -> String {
let mut s: HashSet<String> = words.iter().cloned().collect();
let mut words = words;
words.sort_by(|a, b| b.len().cmp(&a.len()).then(a.cmp(b)));

fn dfs(w: String, s: &mut HashSet<String>) -> bool {
if w.is_empty() {
return true;
}
for k in 1..=w.len() {
if s.contains(&w[0..k]) && dfs(w[k..].to_string(), s) {
return true;
}
}
false
}
for w in words {
s.remove(&w);
if dfs(w.clone(), &mut s) {
return w;
}
}
String::new()
}
}
58 changes: 18 additions & 40 deletions lcci/17.15.Longest Word/Solution.swift
Original file line number Diff line number Diff line change
@@ -1,57 +1,35 @@
class Trie {
var children = [Trie?](repeating: nil, count: 26)
var isEnd = false

func insert(_ word: String) {
var node = self
for ch in word {
let index = Int(ch.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
node.children[index] = Trie()
class Solution {
func longestWord(_ words: [String]) -> String {
var s: Set<String> = Set(words)
var words = words
words.sort { (a, b) -> Bool in
if a.count == b.count {
return a < b
} else {
return a.count > b.count
}
node = node.children[index]!
}
node.isEnd = true
}

func search(_ word: String) -> Bool {
var node = self
for ch in word {
let index = Int(ch.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
return false
}
node = node.children[index]!
}
return node.isEnd
}
}

class Solution {
func longestWord(_ words: [String]) -> String {
var words = words.sorted(by: { $0.count < $1.count || ($0.count == $1.count && $0 > $1) })
let trie = Trie()

var dfs: ((String) -> Bool)!
dfs = { w in
func dfs(_ w: String) -> Bool {
if w.isEmpty {
return true
}
for i in 1...w.count {
if trie.search(String(w.prefix(i))) && dfs(String(w.suffix(w.count - i))) {
for k in 1...w.count {
let prefix = String(w.prefix(k))
if s.contains(prefix) && dfs(String(w.dropFirst(k))) {
return true
}
}
return false
}

var ans = ""

for w in words {
s.remove(w)
if dfs(w) {
ans = w
return w
}
trie.insert(w)
}
return ans

return ""
}
}
26 changes: 26 additions & 0 deletions lcci/17.15.Longest Word/Solution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
function longestWord(words: string[]): string {
const s = new Set(words);

words.sort((a, b) => (a.length === b.length ? a.localeCompare(b) : b.length - a.length));

const dfs = (w: string): boolean => {
if (w === '') {
return true;
}
for (let k = 1; k <= w.length; ++k) {
if (s.has(w.substring(0, k)) && dfs(w.substring(k))) {
return true;
}
}
return false;
};

for (const w of words) {
s.delete(w);
if (dfs(w)) {
return w;
}
}

return '';
}