From 1ba0668dbcf5bc4c40d99ac963711e35797c8efa Mon Sep 17 00:00:00 2001 From: Michael Abed Date: Mon, 9 Apr 2012 01:45:23 -0400 Subject: finished assignment --- Q2.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Q2.cpp (limited to 'Q2.cpp') diff --git a/Q2.cpp b/Q2.cpp new file mode 100644 index 0000000..956c343 --- /dev/null +++ b/Q2.cpp @@ -0,0 +1,49 @@ + +#include + +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; +} -- cgit v1.2.3