- 题目描述:
-
Find a longest common subsequence of two strings.
- 输入:
-
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
- 输出:
-
For each case, output k – the length of a longest common subsequence in one line.
- 样例输入:
-
abcd cxbydz
- 样例输出:
-
2
1 import java.util.Scanner; 2 3 4 public class Main{ 5 public static void main(String[]args){ 6 Scanner in=new Scanner(System.in); 7 while(in.hasNext()){ 8 String x=in.nextLine(); 9 String y=in.nextLine(); 10 int lenx=x.length(); 11 int leny=y.length(); 12 int[][]F=new int[lenx+1][leny+1]; 13 for(int i=0;i<=lenx;i++) F[i][0]=0; 14 for(int i=0;i<=leny;i++) F[0][i]=0; 15 for(int i=1;i<=lenx;i++){ 16 char cx=x.charAt(i-1); 17 for(int j=1;j<=leny;j++){ 18 char cy=y.charAt(j-1); 19 if(cx==cy){ 20 F[i][j]=F[i-1][j-1]+1; 21 } 22 else{ 23 F[i][j]=Math.max(F[i-1][j],F[i][j-1]); 24 } 25 } 26 } 27 System.out.println(F[lenx][leny]); 28 } 29 } 30 } 31 32 /************************************************************** 33 Problem: 1042 34 User: 0000H 35 Language: Java 36 Result: Accepted 37 Time:80 ms 38 Memory:15432 kb 39 ****************************************************************/
时间: 2024-10-13 19:01:33