首先,很感谢仲达兄提供的算法思想,我是用了他的思想,才写出了这个用java求解的动态规划思想求解最长公共字串
仲达兄的博客地址是:http://blog.youkuaiyun.com/liufeng_king/article/details/8528858
再次感谢。
最长公共子串跟最长公共子序列是不一样的。最长字串要求要连接在一起,二子序列是不用的
public class LCSStrFromWen {
public static void main(String[] args) {
String S="hellotcl";
String T="tclhel";
System.out.println(getLCS(S,T));
public static String getLCS(String S, String T) {
>//第一步:创建一个二维的字符串数组,用来保存比较S T两个字符串中每一个char的结果
<span style="white-space:pre"> </span>String[][] temp = new String[T.length()][S.length( </span>char charS;
char charT;
int S_len = S.length();int T_len = T.length();
<int max_len = 0;//这个变量用来存储当前最大字串的长度
<span style="white-space:pre"> </span>for (int i = 0; i < T_len; i++) {//用T串去比较S串中的每一个字符
<span style="white-space:pre"> </span>for (int j = 0; j < S_len; j++)
<span style="white-space:pre"> </span>charT = T.charAt(i);//暂存要比较的字符
<span style="white-space:pre"> </span>charS = S.charAt(j);//同上
<span style="white-space:pre"> </span>if (charT != charS) {//不相等的时候,就在上面的数组中存入空字符串
<span style="white-space:pre"> </span>temp[i][j] = " ";
<span style="white-space:pre"> </span>} else {
<span style="white-space:pre"> </span>if (i == 0 || j == 0) {
<span style="white-space:pre"> </span>temp[i][j] = String.valueOf(charS);//相等的时候,要判断当前的位置
<span style="white-space:pre"> </span>} else {
<span style="white-space:pre"> </span>//动态规划的最重要的思想,如果当前不是i=0,j=0的状态时,存入的是斜对角的+当前的
<span style="white-space:pre"> </span>temp[i][j] = temp[i - 1][j - 1] + String.valueOf(charS);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if (temp[i][j].length() > max_len) {//判断当前的最长字符串
<span style="white-space:pre"> </span>max_len = temp[i][j].length();
<span style="white-space:pre"> </span>LCS = temp[i][j];
<span style="white-space:pre"> </span>}else if(temp[i][j].length() == max_len){
<span style="white-space:pre"> </span>LCS=LCS+","+temp[i][j];//如果有多个最长字符串,合并在一起输出
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return LCS;
}
}