Let’s say I have two strings:
"hello"
"love"
The size of the maximum subarray in the strings is 2: “lo”.
Here’s another example:
"ABBABBA"
"BBABCBA"
Maximum subarray: "BBAB"
Size: 4
Basically, how can I solve this problem in the most efficient way?
My idea is the following:
- Generate all subarrays for one string
- Generate all subarrays for the other string;
- Compare all subarrays
- The result is the size of the largest matching subarrays
But I think this is some bad-looking brute force. Any idea of how I can improve this?
Thank you!
EDIT
I’ll need the string too.
This is a well-known problem called Longest Common Substring. It can be solved in
O(mn), wheremandnare lengths of the individual strings, using dynamic programming approach. The article in Wikipedia contains easy-to-follow pseudocode.