Reputation: 45
I've already made a solution, but I need an optimised solution. The task is to:
The solution I've already made:
int check(string A, string B)
{
string s3;
int flag=0 ,len1,len2,k=0;
s3[0]='\0';
cin>>A>>B;
len1=A.length();
len2=B.length();
for(int i=0;i<len1;i++)
{
k=len1-i;
for(int j=1;j<k;j++ )
{
s3=A.substr(i,j);
size_t found=B.find(s3);
if(found!=string::npos)
{
flag=1;
return flag;
}
}
}
}
Upvotes: 3
Views: 3594
Reputation: 881
Put all characters of the first string into a hash set (unordered_set), then iterate on characters of second string and check if any of them exist in the hash set. If so, then there exists a common substring (of length 1 at least) otherwise, there is no common substring.
Upvotes: 1
Reputation: 1904
bool check(const std::string & a, const std::string & b) {
return b.find_first_of(a) != std::string::npos;
}
You see, if string b
doesn't contain a substring with size 1 from a
it just can't contain a larger substring beginning with the same symbol. So you just basically need to check if string b
contains any symbol from string a
.
Upvotes: 1
Reputation: 4835
Your code has other issues besides optimized solution. For eg not all code paths return a value.
The most efficient solution depends on number of factors including the size of the two strings, how much the two strings match etc.
In absence of these information I propose that you could either use:
Other approaches that you can consider includes modifying rabin karp which shouldn't be very hard to figure out.
Upvotes: 1