First of all, it is not a substring matching problem - it is a problem of finding common characters between two strings.
Your solution works in O (n * m) , where n = len1 and m = len2 in your code. You can easily solve the same problem in O (n + m + c) time by counting the characters in each of the lines (where c is equal to the size of the character set). This algorithm is called sorting counting .
Example code that implements this in your case:
#include <iostream> #include <cstring> // for strlen and memset const int CHARLEN = 256; //number of possible chars using namespace std; // returns table of char duplicates char* find_duplicates(const char* str_1, const char* str_2, const int len1, const int len2) { int *count_1 = new int[CHARLEN]; int *count_2 = new int[CHARLEN]; char *duplicates = new char[CHARLEN+1]; // we hold duplicate chars here int dupl_len = 0; // length of duplicates table, we insert '\0' at the end memset(count_1,0,sizeof(int)*CHARLEN); memset(count_2,0,sizeof(int)*CHARLEN); for (int i=0; i<len1; ++i) { ++count_1[str_1[i]]; } for (int i=0; i<len2; ++i) { ++count_2[str_2[i]]; } for (int i=0; i<CHARLEN; ++i) { if (count_1[i] > 0 && count_2[i] > 0) { duplicates[dupl_len] = i; ++dupl_len; } } duplicates[dupl_len]='\0'; delete count_1; delete count_2; return duplicates; } int main() { const char* str_1 = "foobar"; const char* str_2 = "xro"; char* dup = find_duplicates(str_1, str_2, strlen(str_1), strlen(str_2)); cout << "str_1: \"" << str_1 << "\" str_2: \"" << str_2 << "\"\n"; cout << "duplicates: \"" << dup << "\"\n"; delete dup; return 0; }
Note that I also sort the output here. If you do not want to do this, you can skip counting characters in the second line and just start comparing duplicates on the go.
If, however, you intend to find several duplicates of the same letter (for example, if "banana" and "arena" should output "aan" instead of "an"), you can simply subtract the amount calculated in the current solution and adjust the output accordingly.
source share