
Sponsored
Sponsored
Brute Force Approach: In this approach, for each word in the words array, we will check whether it is a subsequence of the string s or not. This is achieved by iterating over the characters of the word and trying to match them sequentially in the string s.
Time Complexity: O(n * m), where n is the length of the string s and m is the average length of the words. Space Complexity: O(1) since it only uses constant extra space.
1public class Solution {
2 public bool IsSubsequence(string s, string word) {
3 int i = 0, j = 0;
4 while (i < s.Length && j < word.Length) {
5 if (s[i] == word[j]) {
6 j++;
7 }
8 i++;
9 }
10 return j == word.Length;
11 }
12
13 public int NumMatchingSubseq(string s, string[] words) {
14 int count = 0;
15 foreach (var word in words) {
16 if (IsSubsequence(s, word)) {
17 count++;
18 }
19 }
20 return count;
21 }
22}This C# solution also adopts a helper function IsSubsequence to verify the subsequence condition for each word. We use a simple iteration through the string and the word characters.
Efficient Group Matching: Group words by their initial characters in a dictionary and iterate over the string s to manage these groups of words, repositioning them towards completion as their current character is matched. This avoids re-checking each word from the beginning every time.
Time Complexity: O(n + m), where n is the length of s and m is the total number of characters across all words. Space Complexity: O(m) due to storage of iterators.
1from collections import defaultdict
2
3def In this Python approach, we store word iterators in a dictionary waiting, initially keyed by their starting character. As we advance through s, we update the waiting list for each character to track partially matched words, dramatically improving efficiency.