Lintcode Longest Common Substring

Source: Internet
Author: User

The original title link is here: http://www.lintcode.com/en/problem/longest-common-substring/#

Topic:

Given, strings, find the longest common substring.

Return the length of it.

The characters in substringShould occur continuously in original string. This was different with subsequence. Example

Given A = "ABCD" , B = "CBCE" , return 2 . "BC"

Challenge

O (n x m) time and memory.

Exercises

Similar to longest Common subsequence.

Dp. Reference http://www.geeksforgeeks.org/longest-common-substring/

DP[I][J] Represents the length of the str1 of I and str2 longest common substring of length J.

Look at the suffix of two substring.

DP[I][J] = dp[i-1][j-1] + 1 if Str1.charat (i-1) = = Str2.charat (j-1).

DP[I][J] = 0. O.w

Time Complexity:o (m*n). Space:o (m*n).

AC Java:

1  Public classSolution {2     /**3      * @paramA, b:two string.4      * @return: The length of the longest common substring.5      */6      Public intlongestcommonsubstring (String A, String B) {7         if(A = =NULL|| B = =NULL){8             return0;9         }Ten         intm =a.length (); One         intn =b.length (); A         int[] DP =New int[M+1] [N+1]; -         intLongest = 0; -          for(inti = 1; i<=m; i++){ the              for(intj = 1; j<=n; J + +){ -                 if(A.charat (i-1) = = B.charat (j-1)){ -DP[I][J] = dp[i-1][j-1]+1; -}Else{ +DP[I][J] = 0; -                 } +Longest =Math.max (Longest, dp[i][j]); A             } at         } -         returnlongest; -     } -}

Lintcode Longest Common Substring

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.