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.
Example 1:
Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] Output: "apple"
Example 2:
Input: s = "abpcplea", dictionary = ["a","b","c"] Output: "a"
Constraints:
1 <= s.length <= 10001 <= dictionary.length <= 10001 <= dictionary[i].length <= 1000s and dictionary[i] consist of lowercase English letters.This approach involves using a two-pointer technique to check if a string from the dictionary is a subsequence of the given string s. We iterate through each word in the dictionary and for each word, use two pointers to traverse through the word and s. If all characters of the word are found in the same order in s, then it's a valid word. We maintain a result variable to track the longest valid word found so far, and if multiple are of the same length, we track the smallest lexicographical order.
The solution defines a helper function isSubsequence that determines if a given word is a subsequence of s by using two pointers: one traversing s and the other traversing the word. The main logic iterates through each word in the dictionary and checks if it is a subsequence, updating the result if it is longer or lexicographically smaller than the previous result.
C++
Java
Python
C#
JavaScript
s. This is because we potentially traverse the entire string for each dictionary word.This approach involves sorting the dictionary by length (descending) and lexicographical order (ascending). By sorting first, you can ensure that you are checking the longest available words first while resolving ties based on the smallest alphabetical order. We then iterate through this sorted list and use a function to check if a word is a valid subsequence of s.
This Python implementation uses sorting to align words by the desirable evaluation order: first longest, then smallest lexicographically. The `is_subsequence` function checks if a word is a subsequence of `s`, as before accomplished using iterators for efficiency.
Java
| Approach | Complexity |
|---|---|
| Two-Pointer Technique |
|
| Sorting and Checking |
|
Longest Word in Dictionary (LeetCode 720. Algorithm Explained) • Nick White • 18,469 views views
Watch 9 more video solutions →Practice Longest Word in Dictionary through Deleting with our built-in code editor and test cases.
Practice on FleetCode