Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Longest common substring 🌟🌟

Solution

Code

int lcs(string &a, string &b){
    int n = a.size(), m = b.size();
    int res = 0;
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            if (i==0 || j==0)
                dp[i][j] = 0;
            else if (a[i - 1] == b[j - 1]){
                dp[i][j] = 1 + dp[i - 1][j - 1];
                res = max(res,dp[i][j]); // change here
            }
            else
                dp[i][j] = 0; // change here
        }
    }
    return res;
}

Reduces Code

int lcs(string &a, string &b){
    int n = a.size(), m = b.size();
    int res = 0;
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (a[i - 1] == b[j - 1]){
                dp[i][j] = 1 + dp[i - 1][j - 1];
                res = max(res,dp[i][j]); 
            }
        }
    }
    return res;
}