/* You are given two string. Find the Largest
Common Substring (not Subsequence).
First, insert all the suffix (suffix of "suffix" are "x",
"ix"......"suffix") of the first string in the "Trie",
then check with the all the second-string-suffix's.
*/
#include<bits/stdc++.h>
using namespace std;
int cnt=1, ans=0, st=0;
string s, ss;
struct node{
int next[26+1];
}ar[10000];
void new_trie(int cur){
for(int i=0; i<=26; i++)
ar[cur].next[i]=-1;
}
void insert(){ // Inserting the first string
int sz=s.size(), cur=0, x;
for(int i=0; i<sz; i++){
x=s[i]-'a';
if(ar[cur].next[x]==-1){
ar[cur].next[x]=cnt;
new_trie(cnt++);
}
cur=ar[cur].next[x];
}
}
void find(int stt){ // Checking with the second string
int sz=s.size(), cur=0, x, c=0;
for(int i=0; i<sz; i++){
x=s[i]-'a';
if(ar[cur].next[x]==-1)
break;
cur=ar[cur].next[x];
c++;
}
if(c>ans){ // when larger counter(c) is found
st=stt;
ans=c;
}
}
int main(){
int sz;
new_trie(0);
cin>>ss; // First String
sz=ss.size();
for(int i=1; i<=sz; i++){
s="";
for(int ii=sz-i; ii<sz; ii++)
s+=ss[ii];
insert();
}
cin>>ss; // Second String
sz=ss.size();
for(int i=1; i<=sz; i++){
s="";
for(int ii=sz-i; ii<sz; ii++)
s=s+ss[ii];
find(sz-i);
}
for(int i=st, cc=1; cc<=ans; i++, cc++)
cout<<ss[i];
return 0;
}
|
Thursday, October 19, 2017
Print Longest Common Substring
Subscribe to:
Post Comments (Atom)
-
#include<bits/stdc++.h> #define ll long long using namespace std ; ll n , k , t_case ; ll bigmod ( ll b , ll p , ll m...
-
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 ...
-
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 3...
This comment has been removed by a blog administrator.
ReplyDelete