/*最长公共子序列
描述
咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。
tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。
其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
输入
第一行给出一个整数N(0<N<100)表示待测数据组数
接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000.
输出
每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。
样例输入
2
asdf
adfsd
123abc
abc123abc
样例输出
3
6*/
方法一:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class nyoj36 {
static int[][] dp = new int[1100][1100];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-- > 0) {
char[] datao = br.readLine().toCharArray();
char[] datat = br.readLine().toCharArray();
int n = datao.length, m = datat.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (datao[i] == datat[j])//相同,左上-右下斜对角,右下=左上+1
dp[i + 1][j + 1] = dp[i][j] + 1;
else<span style="white-space:pre"> </span>//不等,右上-左下,取一个大的给右下
dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
}
}
System.out.println(dp[n][m]);
}
}
}
方法二:LCS问题转换成LIS问题:
<pre name="code" class="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class nyoj36_2 {
static int[] temp = new int[10000];
static int count;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-- > 0) {
count = 0;
char[] dto = br.readLine().toCharArray();
char[] dtt = br.readLine().toCharArray();
// 将dto的字符在dtt里找出来下标,并且从大到小,将下标存在temp数组里
for (int i = 0; i < dto.length; i++)
for (int j = dtt.length - 1; j >= 0; j--)
if (dto[i] == dtt[j])
temp[count++] = j + 1;
// 当temp数组完成了,那么LCS问题转化为LIS问题了,用二分查找
int len = 1;
int[] t = new int[count];
t[1] = temp[0];
for (int i = 1; i < count; i++) {
int left = 1, right = len;
while (left <= right) {
int mid = (left + right) >> 1;
if (t[mid] < temp[i])
left = mid + 1;
else if (t[mid] > temp[i])
right = mid - 1;
else {
left = mid;
break;
}
}
t[left] = temp[i];
if (left > len)
len = left;
}
System.out.println(len);
}
}
}