The longest common string (JAVA) for string A and string b

Source: Internet
Author: User

Idea: Introduce the idea of a matrix, the string A (length m) as a matrix of rows, the string B (length n) when the matrix column, so that constitutes a m*n matrix. If the node of the matrix corresponds to the same character, i.e. M[i]=n[j], the node value is 1, the current character is the value of the same node = the upper-left corner (D[i-1, J-1]), and the value of the current node is the maximum common substring length. You can intercept the maximum substring simply by the line number and the maximum value.

 PublicStringgetlongest(String s1,string S2) {if(s1==NULL|| s2==NULL){return NULL; }if(S1.equals (S2)) {returnS1; }intLength =0;intEnd =0;int[] A =New int[S1.length ()] [S2.length ()];Char[] Char1=s1.tochararray ();Char[] Char2=s2.tochararray (); for(inti =0; I < s1.length (); i++) { for(intj =0; J < S2.length (); J + +) {intn = (I-1>=0&& J-1>=0) ? A[i-1][j-1] :0;//Current value is the last node value plus 1 a[i][j]=a[i-1][j-1]+1;A[I][J] = (char1[i] = = Char2[j])?1+n:0;//Determine if the longest string length is greater than before                if(A[i][j] > length) {//Hold length as the longest public string lengthlength = A[i][j];//end to the end of the longest public stringend = i; }              }          }returnS1.substring (End-length +1, end+1); }

The longest common string (JAVA) for string A and string b

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.