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.
/*** 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)