求子序列:(输出字符串长度)
int len1, len2;
const int n = 1002;
int b[n][n];
int c[n][n];
char s1[n], s2[n];
void LCSL() {
for (int i = 1; i <= len1; i++)
for (int j = 1; j <= len2; j++) {
if (s1[i - 1] == s2[j - 1]) {
b[i][j] = 1;
c[i][j] = c[i - 1][j - 1] + 1;
}
else if (c[i - 1][j] >= c[i][j - 1]) {
b[i][j] = 2;
c[i][j] = c[i - 1][j];
}
else {
b[i][j] = 3;
c[i][j] = c[i][j - 1];
}
}
}
void print(int i, int j) {
if (i == 0 || j == 0) return;
if (b[i][j] == 1)
{
print(i - 1, j - 1);
cout << s1[i - 1];
}
else if (b[i][j] == 2) {
print(i - 1, j);
}
else
print(i, j - 1);
}
int main()
{
cout << "input s1 and s2";
cin >> s1;
cout << "s2:";
cin >> s2;
len1 = strlen(s1);
len2 = strlen(s2);
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
c[0][j] = 0;
c[i][0] = 0;
}
}
LCSL();
print(len1, len2);
}
求长度:
public static int getLCS(char[] x, char[] y) {
int dp[][] = new int[x.length+1][y.length+1];
int resultLCS = 0;
for (int i = 1; i <= x.length; i++) {
for (int j = 1; j <= y.length; j++) {
if (x[i-1] == y[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
resultLCS = Math.max(resultLCS, dp[i][j]);
} else {
dp[i][j] = 0;
}
}
}
return resultLCS;
}
求最长公共子串:若有多个,输出在较短串中最先出现的那个。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str1=in.nextLine();
String str2=in.nextLine();
String ans="";
String temp="";
if (str1.length() > str2.length()) {
temp = str1;
str1 = str2;
str2 = temp;
}
int m = str1.length() + 1;
int n = str2.length() + 1;
int[][] dp = new int[m][n];
int max = 0;
int index = 0;
for (int i=1; i < m; i++) {
for (int j=1; j < n; j++) {
if (str1.charAt(i-1) == str2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + 1;
if (dp[i][j] > max) {
max = dp[i][j];
index = i;
}
}
}
}
System.out.println(str1.substring(index-max, index));
}