Advertisement
sweet1cris

Untitled

Jan 9th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. // 严格的说,这个算法是递推,而不是动态规划,但是可以用动态规划的四要素去分析换个解答。
  2. // 为什么不是动态规划?因为最暴力的方式也就是 O(n^3) 可以找到A所有的Substring然后看看在不在B里。
  3. public class Solution {
  4.     /**
  5.      * @param A, B: Two string.
  6.      * @return: the length of the longest common substring.
  7.      */
  8.     public int longestCommonSubstring(String A, String B) {
  9.         // state: f[i][j] is the length of the longest lcs
  10.         // ended with A[i - 1] & B[j - 1] in A[0..i-1] & B[0..j-1]
  11.         int n = A.length();
  12.         int m = B.length();
  13.         int[][] f = new int[n + 1][m + 1];
  14.        
  15.         // initialize: f[i][j] is 0 by default
  16.        
  17.         // function: f[i][j] = f[i - 1][j - 1] + 1 or 0
  18.         for (int i = 1; i <= n; i++) {
  19.             for (int j = 1; j <= m; j++) {
  20.                 if (A.charAt(i - 1) == B.charAt(j - 1)) {
  21.                     f[i][j] = f[i - 1][j - 1] + 1;
  22.                 } else {
  23.                     f[i][j] = 0;
  24.                 }
  25.             }
  26.         }
  27.        
  28.         // answer: max{f[i][j]}
  29.         int max = 0;
  30.         for (int i = 1; i <= n; i++) {
  31.             for (int j = 1; j <= m; j++) {
  32.                 max = Math.max(max, f[i][j]);
  33.             }
  34.         }
  35.        
  36.         return max;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement