• + 0 comments

    quadratic time O(A.size() * B.size())

    int LCSReturns(const string& A, const string& B) {
        int total = 0;
        vector<vector<int>> cache(A.size() + 1, vector<int>(B.size() + 1)), reverse(A.size() + 2, vector<int>(B.size() + 2));
        vector<vector<bool>> insertion(A.size() + 2, vector<bool>(75));
        for (int i = 1; i <= A.size(); i++) {
            for (int j = 1; j <= B.size(); j++) {
                if (A[i - 1] == B[j - 1]) cache[i][j] = cache[i - 1][j - 1] + 1;
                else cache[i][j] = max(cache[i - 1][j], cache[i][j - 1]);
            }
        }
        for (int i = A.size(); i >= 1; i--) {
            for (int j = B.size(); j >= 1; j--) {
                if (A[i - 1] == B[j - 1]) reverse[i][j] = reverse[i + 1][j + 1] + 1;
                else reverse[i][j] = max(reverse[i + 1][j], reverse[i][j + 1]);
            }
        }
        for (int i = 1; i <= A.size() + 1; i++) {
            for (int j = 1; j <= B.size(); j++) {
                if (insertion[i][B[j - 1] - '0']) continue;
                if (cache[i - 1][j - 1] + reverse[i][j + 1] == cache[A.size()][B.size()]) {
                    insertion[i][B[j - 1] - '0'] = true;
                    total++;
                }
            }
        }
        return total;
    }