1. 程式人生 > >Longest Common Substring

Longest Common Substring

long strings sta www. charat 分情況討論 ron cnblogs 最優解

Given two strings, find the longest common substring.

Return the length of it.

 Notice

The characters in substring should occur continuously in original string. This is different with subsequence.

Have you met this question in a real interview? Yes
Example
Given A = "ABCD", B = "CBCE", return 2
. Challenge O(n x m) time and memory.

區別於 Longest Common Subsequence 這是累加求subString 的

狀態設為遍歷到當前的i, j時的結果值, 但是卻是不對, 是因為求得是累加的值,

Input "www.lintcode.com code", "www.ninechapter.com code" Output 17 Expected 9
for (int i = 1; i <= n; i++) {
           for (int j = 1; j <= m; j++) {
                f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
                if (A.charAt(i - 1) == B.charAt(j - 1)) {
                    f[i][j] = Math.max(f[i - 1][j - 1] + 1, f[i][j]);
                } 
            
            }
        }

和這樣寫無差異, 都是求的累加和.

if (A.charAt(i - 1) == B.charAt(j - 1)) {
                    f[i][j] = f[i - 1][j - 1] + 1;
                } else {
                    f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
                }

因此要改下狀態(根據結果來設定狀態需要那幾個變量表示, 這個狀態跟), : 匹配到的字符是最後一個字符的結果值(作為局部變量 ) + 全局變量

常見狀態:

1遍歷到當前字符時的最優解,

2 遍歷到當前字符,字符如果是題意要求的string的局部解

方程: 分情況討論, 根據題意與當前字符的形態和上個狀態做轉化

public int longestCommonSubstring(String A, String B) {
        // write your code here
        //state
        int n = A.length();
        int m = B.length();
        int[][] f = new int[n + 1][m + 1];
        //initialize
        for (int i = 0; i <= n; i++) {
            f[i][0] = 0;
        }
        for (int i = 0; i <= m; i++) {
            f[0][i] = 0;
        }
        int ans = 0;
        //function
        for (int i = 1; i <= n; i++) {
           for (int j = 1; j <= m; j++) {
            if (A.charAt(i - 1) == B.charAt(j - 1)) {
                f[i][j] = f[i - 1][j - 1] + 1;
            } else {
                f[i][j] = 0;
            }
            ans = Math.max(f[i][j], ans);
            
        }
        }
        return ans;
    }

  

 

Longest Common Substring