-
Notifications
You must be signed in to change notification settings - Fork 0
/
numMatchingSubseq.cpp
73 lines (68 loc) · 1.61 KB
/
numMatchingSubseq.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// bucket
char*cursor[26][50001];
int len[26];
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
memset(len,0,sizeof(len));
for(int i=0;i<words.size();i++){
int c=words[i][0]-'a';
cursor[c][len[c]++]=&words[i][0];
}
int ans=0;
for(char c:S){
c-='a';
int k=len[c];
len[c]=0;
for(int i=0;i<k;i++){
char*next=cursor[c][i]+1;
if(!*next)ans++;
else{
int d=*next-'a';
cursor[d][len[d]++]=next;
}
}
}
return ans;
}
};
int _IO=[](){
ios::sync_with_stdio(0);
cin.tie(0); //cout.tie(0);
return 0;
}();
// appearance of ch after pos i
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words)
{
int m = S.size();
S = "#"+S;
int next[m+1][26];
for (int k=0; k<26; k++)
next[m][k] = -1;
for (int i=m; i>=1; i--)
{
for (int k=0; k<26; k++)
next[i-1][k] = next[i][k];
next[i-1][S[i]-'a'] = i;
}
int ret = 0;
for (auto word: words)
{
int flag = 1;
int i = 0;
for (auto ch: word)
{
i = next[i][ch-'a'];
if (i==-1)
{
flag = 0;
break;
}
}
if (flag) ret++;
}
return ret;
}
};