Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Matching Subsequences in C++
Suppose we have a string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. So if the input is S= “abcde” and dictionary is [“a”, “bb”, “acd”, “ace”], then output will be 3. Because there are three sequence of words in the dictionary, that are a subsequence of S: “a” “acd” and “ace”
To solve this, we will follow these steps −
- n := size of words array
- create one map m
- for i in range 0 to size of words
- insert words[i] into the map m[words[i, 0]] position
- ans := 0
- for i in range 0 to size of S
- char x := S[i]
- if x is present in the map m, then
- temp := m[x], and delete m[x]
- for j in range 0 to temp size
- if size of temp[j] = 1, then increase ans by 1, otherwise insert substring of temp[j] from index 1 into m[temp[j, 1]]
- return ans
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
int n = words.size();
map <char, vector <string> > m;
for(int i = 0; i < words.size(); i++){
m[words[i][0]].push_back(words[i]);
}
int ans = 0;
for(int i = 0; i < S.size(); i++){
char x = S[i];
if(m.find(x) != m.end()){
vector <string> temp = m[x];
m.erase(x);
for(int j = 0; j < temp.size(); j++){
if(temp[j].size() == 1){
ans++;
} else {
m[temp[j][1]].push_back(temp[j].substr(1));
}
}
}
}
return ans;
}
};
int main() {
Solution ob1;
string s = "abcde";
vector<string> v{"a","bb","acd","ace"};
cout << ob1.numMatchingSubseq(s, v) << endl;
return 0;
}
Input
"abcde"
["a","bb","acd","ace"]
string s = "abcde";
vector<string> v{"a","bb","acd","ace"};
Output
3
Advertisements