题目描述:
一个字符串A的子串被定义成从A中顺次选出若干个字符构成的串。如A=“cdaad" ,顺次选1,3,5个字符就构成子串" cad" ,现给定两个字符串,求它们的最长共公子串。
代码:
package lanqiao;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] cs1 = sc.next().toCharArray();
char[] cs2 = sc.next().toCharArray();
int[][] c = new int[cs1.length + 1][cs2.length + 1];
int max = 0;
for(int i = 1;i < c.length;i ++)
{
for(int j = 1;j < c[i].length;j ++)
{
if(cs1[i - 1] == cs2[j - 1])
c[i][j] = c[i - 1][j - 1] + 1;
else{
c[i][j] = Math.max(c[i - 1][j],c[i][j - 1]);
}
if(c[i][j] > max)
{
max = c[i][j];
}
}
}
System.out.println(max);
}
}