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.1using System;
2using System.Collections.Generic;
3
4public class LongestWordFinder {
5 public string FindLongestWord(string s, IList<string> dictionary) {
6 string result = "";
7 foreach (string word in dictionary) {
8 if (IsSubsequence(s, word)) {
9 if (word.Length > result.Length || (word.Length == result.Length && string.Compare(word, result) < 0)) {
10 result = word;
11 }
12 }
13 }
return result;
}
private bool IsSubsequence(string s, string word) {
int i = 0, j = 0;
while (i < s.Length && j < word.Length) {
if (s[i] == word[j]) {
j++;
}
i++;
}
return j == word.Length;
}
public static void Main(string[] args) {
LongestWordFinder finder = new LongestWordFinder();
string s = "abpcplea";
IList<string> dictionary = new List<string> { "ale", "apple", "monkey", "plea" };
Console.WriteLine(finder.FindLongestWord(s, dictionary));
}
}
The C# solution uses a similar two-pointer approach to check if the word is a subsequence of the given string s
. We ensure that we collect the longest word available by comparing lengths and lexicographic order.
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
.
1def is_subsequence(s, word):
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.