diff options
Diffstat (limited to 'Q2.cpp')
-rw-r--r-- | Q2.cpp | 49 |
1 files changed, 49 insertions, 0 deletions
@@ -0,0 +1,49 @@ + +#include <iostream> + +char *largestCommonSubstr(const char s1[], const char s2[]); + +using namespace std; +int main(int argc, const char *argv[]) +{ + + const char *s1[] = {"Boston", "James", "computer" , "abc", "software"}; + const char *s2[] = {"Killington", "Thames", "Counter", "abba", "MICROSOFT"}; + + for (int i = 0; i < 5; i++) { + char *substr = largestCommonSubstr(s1[i], s2[i]); + if (substr) + cout << "longest common substring of " << s1[i] << " and " << s2[i] << " is " << substr << endl; + else + cout << "no common substrings between " << s1[i] << " and " << s2[i] << endl; + } + + return 0; +} + +char *largestCommonSubstr(const char s1[], const char s2[]) +{ + int len = 0; + int longest = 0; + int longestpos; + int pos1,pos2,ofst; + + for (pos1 = 0; s1[pos1]; pos1++) { + for (pos2 = 0; s2[pos2]; pos2++) { + for (ofst = 0,len=0; s1[pos1+ofst] == s2[pos2+ofst++]; len++) {} + if (len > longest) { + longest = len; + longestpos = pos1; + } + } + } + + char *result = longest != 0 ? new char(longest+1) : NULL; + if (result) { + for (int i = 0; i < longest; i++) { + result[i] = s1[longestpos+i]; + } + result[longest] = '\0'; + } + return result; +} |