• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: Longest Common Substring

Given two strings, find the longest common substring.

Return the length of it.

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

Example
Given A=“ABCD”, B=“CBCE”, return  2
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 strings.
 4      * @return: The length of longest common subsequence of A and B.
 5      */
 6     public int longestCommonSubstring(String A, String B) {
 7         // write your code here
 8         int[][] res = new int[A.length()+1][B.length()+1];
 9         int result = 0;
10         for (int i=0; i<=A.length(); i++) {
11             for (int j=0; j<=B.length(); j++) {
12                 if (i==0 || j==0) {
13                     res[i][j] = 0;
14                     continue;
15                 }
16                 if (A.charAt(i-1) != B.charAt(j-1)) res[i][j] = 0;
17                 else res[i][j] = res[i-1][j-1]+1;
18                 result = Math.max(result, res[i][j]);
19             }
20         }
21         return result;
22     }
23 }

 

posted @ 2015-03-09 11:33  neverlandly  阅读(447)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3