nyoj 36 最长公共子序列【Java】

最长公共子序列【Java】


时间限制:3000 ms | 内存限制:65535 KB
难度:3

描述

咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。
tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
输入
第一行给出一个整数N(0<N<100)表示待测数据组数
接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000.
输出
每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。

样例输入

2
asdf
adfsd
123abc
abc123abc

样例输出

3
6

代码

import java.util.Scanner;

public class Main {
	private static String str3;
	private static String str4;

	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		int number = cin.nextInt();
		cin.nextLine();
		while (number > 0) {
			String str1 = cin.nextLine();
			String str2 = cin.nextLine();
			int[][] arr = new int[str1.length() + 1][str2.length() + 1];
			for (int i = 1; i <= str1.length(); i++) {
				for (int j = 1; j <= str2.length(); j++) {
					if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
						arr[i][j] = arr[i - 1][j - 1] + 1;
					} else {
						arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
					}
				}
			}
			System.out.println(arr[str1.length()][str2.length()]);
			number--;
		}

		cin.close();
	}

	public static int function(int i, int j) {
		if (i == -1 || j == -1)
			return 0;
		if (str3.charAt(i) == str4.charAt(j))
			return 1 + function(i - 1, j - 1);
		return Math.max(function(i - 1, j), function(i, j - 1));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值