The longest common substring problem can be easily solved using a matrix approach.
A simple google search will show the process.
Here is a working C++ code of the same:
A simple google search will show the process.
Here is a working C++ code of the same:
/*
Copyright: Puneet Sohi
*/
#include <iostream>
#include <string>
#include <vector>
#include <tr1/unordered_map>
using namespace std;
using namespace tr1;
void findLongestCommonSubstring(string s1, string s2){
if (s1.size() == 0 || s2.size() == 0){
cout << "input NULL, no common substring!"<< endl;
}
int i = 0;
int j = 0;
int a[100][100];
//int a[s1.size()+1][s2.size()+1];
string l_substr;
int l_count=0;
int temp;
while(i<s1.size()){
//cout << "entry1" << endl;
j=0;
while(j<s2.size()){
//cout << "entry2" << endl;
//cout << "i: " << i << "j: " << j << endl;
if(s1[i] == s2[j]){
cout << "match at i: "<< i << " j: " << j << endl;
//cout << "a[i][j] = "<< a[i][j] << endl;
a[i+1][j+1] = a[i][j]+1;
//cout << "a[i+1][j+1]"<< a[i+1][j+1] << endl;
temp = a[i+1][j+1];
cout << "temp: " << temp << endl;
if(temp > l_count){
//new longest count found
l_count = temp;
l_substr = s1.substr(i-temp+1, temp);
cout << "new longest substr found, " << "lcount: " << l_count << endl;
cout << "Substr: " << l_substr << endl;
}
}
j++;
}
i++;
}
cout << "length of longest common substring: " << l_count << endl;
cout << "longenst common substring is: "<< l_substr << endl;
return;
}
int main () {
string s1 = "adfdfdsfahardyadffadsf";
string s2 = "hardyplokmijn"; //o/p shud be hardyharhar
findLongestCommonSubstring(s1, s2);
return 0;
}
No comments:
Post a Comment