[Data structure and algorithm] LCS (continuous)

Source: Internet
Author: User

This year, Alibaba's pen test questions come with a continuous public substring.

Thought 1: At that time, my first response was to find out all the substrings of a shorter string and then use these substrings (first with a longer length) remove long strings for matching. Later I thought the efficiency was too low.

Train of Thought 2: To solve the discontinuous LCS problem, first fill in the table and then find it in the table.

  • Code Implementation

/*** Source code name: lcstring. java * Date: 2014-09-02 * program function: LCs (continuous) * copyright: [email protected] * a2bgeek */public class lcstring {private string MoNE, mtwo; int [] [] mmatrix; string mresult; int mmaxindex, mmaxlength; Public lcstring (string one, string two) {mone = one; mtwo = two; int lengthone = one. length (); int lengthtwo = two. length (); mmatrix = new int [lengthone + 1] [lengthtwo + 1]; mresult = "" ;}public void generatematrix () {int lengthone = mone. length (); int lengthtwo = mtwo. length (); For (INT I = 1; I <= lengthone; I ++) {mmatrix [I] [0] = 0;} For (Int J = 1; j <= lengthtwo; j ++) {mmatrix [0] [J] = 0;} mmatrix [0] [0] = 0; For (INT I = 1; I <= lengthone; I ++) {for (Int J = 1; j <= lengthtwo; j ++) {If (MoNE. charat (I-1) = mtwo. charat (J-1) {mmatrix [I] [J] = mmatrix [I-1] [J-1] + 1 ;} else {mmatrix [I] [J] = 0;} If (mmatrix [I] [J]> mmaxlength) {mmaxlength = mmatrix [I] [J]; mmaxindex = I ;}}} public void getlcstring () {for (INT I = 0; I <mmaxlength; I ++) {mresult + = mone. charat (mmaxindex-1-mmaxlength + 1 + I) ;}} public static void main (string [] ARGs) {string one = "abgfcdeij"; string two = "knkcdegou "; lcstring = new lcstring (ONE, TWO); lcstring. generatematrix (); lcstring. getlcstring (); system. out. println (lcstring. mresult );}}


[Data structure and algorithm] LCS (continuous)

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.