LCS模板题,但是注意输入不只一行,需要hasNextLine()循环一下。


import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
        String []str = sc.nextLine().split(" ");
        String str1 = str[0];
        String str2 = str[1];
        int str1length = str1.length();
        int str2length = str2.length();
        int [][]dp = new int[str1length+1][str2length+1];
        for(int i = 1;i<=str1length;i++){
            for(int j = 1;j<=str2length;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]);
            }
        }

        // for(int i = 1;i<=str1length;i++){
        //     for(int j = 1;j<=str2length;j++){
        //         System.out.print(dp[i][j]+" ");
        //     }
        //     System.out.println();
        // }
        System.out.println(dp[str1length][str2length]);
    }
}
}