Leetcode 524. Longest Word in Dictionary through Deleting
Given a string s
and a string dictionary d
, you need to find the longest string in the dictionary that can be formed by deleting some characters of the given string. 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.
Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]
Output:
"a"
Note:
To solve this problem, we need to:
s
.Key steps:
import java.util.*;
public class Solution {
public String findLongestWord(String s, List<String> dictionary) {
String longestWord = "";
for (String word : dictionary) {
if (isSubsequence(word, s)) {
if (word.length() > longestWord.length() ||
(word.length() == longestWord.length() && word.compareTo(longestWord) < 0)) {
longestWord = word;
}
}
}
return longestWord;
}
private boolean isSubsequence(String word, String s) {
int i = 0; // Pointer for word
int j = 0; // Pointer for s
while (i < word.length() && j < s.length()) {
if (word.charAt(i) == s.charAt(j)) {
i++;
}
j++;
}
return i == word.length();
}
public static void main(String[] args) {
Solution sol = new Solution();
List<String> dictionary = Arrays.asList("ale", "apple", "monkey", "plea");
System.out.println(sol.findLongestWord("abpcplea", dictionary)); // Outputs: "apple"
}
}
O(n + m)
where n
is the length of word
and m
is the length of s
.O(k)
, where k
is the number of words in the dictionary.Combining these complexities, the overall time complexity:
L_dict
be the maximum length of words in the dictionary.N
is the length of s
.k
words, the complexity will be O(k * (N + L_dict))
.This works efficiently within the problem constraints.
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?