最长公共子序列(可以断续)
0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1
0 1 2 2 2 2 2 2
0 1 2 3 3 3 3 3
0 1 2 3 4 4 4 4
0 1 2 3 4 4 4 4
0 1 2 3 4 4 5 5
0 1 2 3 4 4 5 6
package com.lzg.flume.intercepter;
import java.util.ArrayList;
import java.util.List;
public class LCS {
public static List<String> getLCSstring(char[] str1, char[] str2) {
int n = str1.length, m = str2.length;
int[][] dp = new int[100][100];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (str1[i - 1] == str2[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 = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
String res= "";
for (int i = n, j = m; i >= 1 && j >= 1; ) {
if (str1[i - 1] == str2[j - 1]) {
String x = String.valueOf(str1[i - 1]);
// res+=x;//不需要重新赋值
res = res.concat(x); //连接之后必须是返回的新字符串,并赋给res索引,否则res一直不变化
i--;
j--;
} else {
if (dp[i][j - 1] >= dp[i - 1][j]) {
j--;
} else {
i--;
}
}
}
System.out.println(new StringBuilder(res).reverse().toString());
return null;
}
public static void main(String[] args) {
String str1 = "qwuio123qw", str2 = "uio789qw";
getLCSstring(str1.toCharArray(), str2.toCharArray());
}
}
最长公共子串(必须连续)
方法1 按照上面代码的继承
0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1
0 1 2 2 2 2 2 2
0 1 2 3 3 3 3 3
0 1 2 3 4 4 4 4
0 1 2 3 4 4 4 4
0 1 2 3 4 4 5 5
0 1 2 3 4 4 5 6
package com.lzg.flume.intercepter;
import java.util.List;
public class LCS1 {
public static List<String> getLCSstring(char[] str1, char[] str2) {
int n = str1.length, m = str2.length;
int[][] dp = new int[100][100];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
String res = "";
int max = 0;
String maxRes = "";
for (int i = n, j = m; i >= 1 && j >= 1; ) {
if (str1[i - 1] == str2[j - 1]) {
String x = String.valueOf(str1[i - 1]);
res += x;
i--;
j--;
} else {
res = "";
if (dp[i][j - 1] >= dp[i - 1][j]) {
j--;
} else {
i--;
}
}
int num = res.length();
if (num > max) {
max = num;
maxRes = res;
}
}
System.out.println(new StringBuilder(maxRes).reverse().toString());
return null;
}
public static void main(String[] args) {
String str1 = "1234567tlkjhgqwuioa", str2 = "1234567ylkjhguioa";
getLCSstring(str1.toCharArray(), str2.toCharArray());
}
}
方法2