#524
Medium Algorithms Longest word in dictionary through deleting
Array Two Pointers String Sorting
52.5% acceptance
Feb 19, 2026
1863
365
Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn find_longest_word(s: String, dictionary: Vec<String>) -> String {
fn is_subseq(word: &[u8], s: &[u8]) -> bool {
let mut j = 0;
for &c in s {
if j < word.len() && word[j] == c { j += 1; }
}
j == word.len()
}
let sb = s.as_bytes();
let mut result = String::new();
for word in &dictionary {
if is_subseq(word.as_bytes(), sb) {
if word.len() > result.len() || (word.len() == result.len() && word < &result) {
result = word.clone();
}
}
}
result
}
}