f[j, 0] = f[j - 1, 0] + 1 // concat solution in f[j - 1, 0] and s1[j]
f[j, 1] = f[j - 1, 1] + 1 // concat solution in f[j - 1, 1] and s1[j]
f[j, 0] = 0 // the only choice is empty string
f[j, 1] = max(f[j - 1, 0] + 1, // concat solution in f[j - 1, 1]0] and s1[j] (or s2[j - i])
And:
f[-1, 0] = f[-1, 1] = 0
Since we only need f[j - 1, :] to calculate f[j, :], only O(1) extra space is used.
#include <string>
#include <cassert>
#include <iostream>
using namespace std;
int main() {
string s1, s2;
getline(cin, s1);
getline(cin, s2);
int n1, n2;
n1 = s1.size();
n2 = s2.size();
int max_len = 0;
int max_end = -1;
for(int i = 1 - n2; i < n1; i++) {
int f0, f1;
int max_len2 = 0;
int max_end2 = -1;
f0 = f1 = 0;
for(int j = max(i, 0), j_end = min(n1, i + n2); j < j_end; j++) {
if(s1[j] == s2[j - i]) {
f0 += 1;
f1 += 1;
} else {
f1 = max(f1, f0 + 1);1;
f0 = 0;
}
if(f1 > max_len2) {
max_len2 = f1;
max_end2 = j + 1;
}
}
if(max_len2 > max_len) {
max_len = max_len2;
max_end = max_end2;
}
}
assert(max_end != -1);
// cout << max_len << endl;
cout << max_end - max_len + 1 << " " << max_end << endl;
}