Click to open Hangzhou electric 1159
Problem Descriptiona subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence x = <x1, x2, ..., xm> another sequence Z = <z1, Z2, ..., zk> is a subsequence of X if there E Xists a strictly increasing sequence <i1, I2, ..., ik> of indices of X such so for all J =,..., K, Xij = ZJ. For example, Z = <a, B, F, c> are a subsequence of X = <a, B, C, F, B, c> with index sequence <1, 2, 4, 6> ;. Given sequences X and y the problem is to find the length of the Maximum-length common subsequence of x and Y.
The program input was from a text file. Each data set in the file contains the strings representing the given sequences. The sequences is separated by any number of white spaces. The input data is correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from th e beginning of a separate line.
Sample Input
ABCFBC abfcabprogramming contest ABCD MNP
Sample Output
420
Code implementation:
Import Java.util.*;class main {static int[][] dp;public static void Main (string[] args) {Scanner sc=new Scanner (system.in) ; while (Sc.hasnext ()) {String str1=sc.next (); String Str2=sc.next (); LCS (STR1,STR2); System.out.println (Dp[str1.length ()][str2.length ());}} public static void LCS (String str1,string str2) {int i,j;dp=new int[str1.length () +1][str2.length () +1];for (i=1;i<= Str1.length (); i++) {for (J=1;j<=str2.length (); j + +) {if (Str1.charat (i-1) ==str2.charat (j-1)) {dp[i][j]=dp[i-1][ j-1]+1;} Else{dp[i][j]=math.max (Dp[i-1][j], dp[i][j-1]);}}}}
Hangzhou Electric 1159 (Common subsequence) LCS and DP