Lintcode: Longest Common Substring 解題報告


Longest Common Substring

原題鏈接: http://lintcode.com/zh-cn/problem/longest-common-substring/#

Given two strings, find the longest common substring.

Return the length of it.

注意

The characters in substring should occur continiously in original string. This is different with subsequnce.

樣例
 

標簽 Expand 

 

SOLUTION 1:

DP:
D[i][j] 定義為:兩個string的前i個和前j個字符串,尾部連到最后的最長子串。
D[i][j] = 
1. i = 0 || j = 0 : 0
2. s1.char[i - 1] = s2.char[j - 1] ? D[i-1][j-1] + 1 : 0;
另外,創建一個max的緩存,不段更新即可。
 1 public class Solution {
 2     /**
 3      * @param A, B: Two string.
 4      * @return: the length of the longest common substring.
 5      */
 6     public int longestCommonSubstring(String A, String B) {
 7         // write your code here
 8         if (A == null || B == null) {
 9             return 0;
10         }
11         
12         int lenA = A.length();
13         int lenB = B.length();
14         
15         // bug 1: use error init.
16         int[][] D = new int[lenA + 1][lenB + 1];
17         
18         int max = 0;
19         
20         // BUG 2: should use <= instead of <
21         for (int i = 0; i <= lenA; i++) {
22             for (int j = 0; j <= lenB; j++) {
23                 if (i == 0 || j == 0) {
24                     D[i][j] = 0;
25                 } else {
26                     if (A.charAt(i - 1) == B.charAt(j - 1)) {
27                         D[i][j] = D[i - 1][j - 1] + 1;
28                     } else {
29                         D[i][j] = 0;
30                     }
31                 }
32                 
33                 max = Math.max(max, D[i][j]);
34             }
35         }
36         
37         return max;
38     }
39 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/dp/LongestCommonSubstring.java

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM