Sponsored
Sponsored
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.
s
. This is because we potentially traverse the entire string for each dictionary word.1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5int isSubsequence(char *s, char
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.
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
.
1import java.util.List;
2
This Java solution follows a similar strategy by first sorting the dictionary by length and lexicographical order. The `isSubsequence` method checks if each word is a subsequence of `s`, and the iterated dictionary gives the first valid longest word directly.