-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstring-pattern.cpp
72 lines (63 loc) · 963 Bytes
/
string-pattern.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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll m=1e6;
ll lps[m];
string pat,str;
void lpsAray(ll l){
ll i=1;
ll length=0;
lps[0]=0; //Always
while(i<l){
if(pat[i] == pat[length]){
length++;
lps[i]=length;
i++;
}
else{
if(length!=0){
length=lps[length-1];
}
else{
lps[i]=0;
i++;
}
}
}
}
void searchPattern(ll ls,ll pl){
ll i=0; //index for string
ll j=0; //index for pattern
while(i<ls){
if(str[i]==pat[j]){
i++;
j++;
}
if(j == pl){
cout<<i-j<<endl;
j=lps[j-1];
}
// j match hone ke bad bhosdi wala nahi mila to
else if( i< ls && str[i]!=pat[j] ){
if(j!=0)
j=lps[j-1];
else
i++;
}
}
}
int main(){
ll n;
while(cin>>n){
cin>>pat>>str;
ll lengthString=str.length();
ll patLength=pat.length();
if(lengthString<patLength)
cout<<" ";
else{
lpsAray(patLength);
searchPattern(lengthString,patLength);
}
}
return 0;
}