1. All Substrings Generation
Intuition
Generate all substrings of s1 and check if they exist in s2.
Algorithm
- For length L from min(m, n) down to 1:
- For start from 0 to m - L:
- Extract substring
sub = s1.substr(start, L). - If
s2.find(sub) != string::npos, return L. - Return 0.
#include <iostream>#include <string>#include <algorithm> using namespace std; int longestCommonSubstringBrute(string s1, string s2) { int m = s1.length(), n = s2.length(); int maxLen = 0; for (int len = min(m, n); len >= 1; len--) { for (int i = 0; i <= m - len; i++) { string sub = s1.substr(i, len); if (s2.find(sub) != string::npos) { return len; } } } return 0;} int main() { string s1 = "ABCDGH", s2 = "ACDGHR"; cout << "Longest Common Substring (Brute): " << longestCommonSubstringBrute(s1, s2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(m^2 * n) - Space complexity:
O(m) substring allocation