Leetcode 524. Longest Word in Dictionary through Deleting
Given a string s
and a string array dictionary
, find the longest string in the dictionary
that can be formed by deleting some characters of the given string s
. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
s
and dictionary
?s
is up to 1000, and dictionary
can contain up to 1000 words.s
and dictionary
lowercase English letters?dictionary
can be formed by deleting characters from s
.dictionary
, check if it can be formed from s
.d
of length m
is a subsequence of s
of length n
is O(n).k
words in the dictionary, the overall time complexity is O(k * n), assuming the length of words in the dictionary is generally much smaller compared to n
.#include <vector>
#include <string>
#include <algorithm>
bool isSubsequence(const std::string& s, const std::string& target) {
int i = 0, j = 0;
while (i < s.size() && j < target.size()) {
if (s[i] == target[j]) {
++j;
}
++i;
}
return j == target.size();
}
std::string findLongestWord(std::string s, std::vector<std::string>& dictionary) {
std::string result;
for (const std::string& word : dictionary) {
if (isSubsequence(s, word)) {
if (word.length() > result.length() ||
(word.length() == result.length() && word < result)) {
result = word;
}
}
}
return result;
}
target
can be formed by deleting characters from s
. It uses two pointers to traverse through s
and target
.dictionary
and uses isSubsequence
to check if the word can be formed from s
.This approach ensures that we efficiently find the longest word from the dictionary that can be constructed by deleting some characters from s
, meeting the constraints and requirements provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?