Lintcode: Longest Common Substring, lintcodelongest

Source: Internet
Author: User

Lintcode: Longest Common Substring, lintcodelongest

Given two strings, find the longest common substring.Return the length of it.NoteThe characters in substring should occur continiously in original string. This is different with subsequnce.ExampleGiven A=“ABCD”, B=“CBCE”, return  2
DP: D [I] [j] is defined as: the first I of two strings and the first j of the string, and the tail is connected to the last eldest son string. D [I] [j] = 1. I = 0 | j = 0: 02. s1.char [I-1] = s2.char [j-1]? D [I-1] [J-1] + 1: 0; in addition, create a max cache without segment update.
 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 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.