Created
December 2, 2016 01:07
-
-
Save bakkiraju/f63f8dd8f51741d07925e8f232b5e19a to your computer and use it in GitHub Desktop.
substring which would be closest (max overlap) to a given prefix and suffix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
int returnMatchCount(const string &s1, const string &s2) | |
{ | |
int cnt = 0; | |
for (int i = s1.length()-1; i >=0; i--) { | |
string sub_sub = s1.substr(i,s1.length()-i); | |
if (std::strncmp(sub_sub.c_str(), s2.c_str(), sub_sub.length()) == 0) { | |
cnt = sub_sub.length(); | |
} | |
} | |
return cnt; | |
} | |
string getMaxTextScoreFor(const string &text, const string &prefix, const string &suffix) | |
{ | |
int max_score = 0; | |
string max_score_string; | |
for (int i=0; i<text.length(); i++) | |
{ | |
for (int sub_str_len=max_score+1; sub_str_len + i <= text.length();sub_str_len++) | |
{ | |
string sub_str = text.substr(i,sub_str_len); | |
int score = returnMatchCount(prefix, sub_str) + returnMatchCount(sub_str, suffix); | |
if (score > max_score) | |
{ | |
max_score = score; | |
max_score_string = sub_str; | |
} else if ( score == max_score) { | |
if (strcmp(sub_str.c_str(), max_score_string.c_str())) | |
max_score_string = sub_str; | |
} | |
} | |
} | |
return max_score_string; | |
} | |
int main(int argc, char *argv[]) { | |
time_t tstart, tend; | |
tstart = time(0); | |
string text = "noahingnothingnoaing"; | |
string prefix = "bruno"; | |
string suffix = "ingenious"; | |
cout << getMaxTextScoreFor(text, prefix, suffix) << endl; | |
tend = time(0); | |
cout << "It took "<< difftime(tend, tstart) <<" second(s)."<< endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment