給定兩個字符串,求出它們之間最長的相同子字符串的長度。
子串要求字符必須是連續的,但是子序列就不是這樣了。。
子序列跟子串的求法類似,都是使用動態規劃的思想,s1每次增加一個字符,看與s2當前位置的字符是不是相同,如果相同做相應的處理,如果不同,做另外的處理。
子序列的處理方式:
相同的情況下,該二維數組的位置等於[i-1][j-1]+1
不同的情況下,該二維數組的位置等於MAX(d[i-1][j],d[i][j-1])
下面描述下子串的求法。
最長公共子串,要求字符是連續的。那麼在[s1每次增加一個字符,看與s2當前位置的字符是不是相同]
相同的情況下,二維數組的位置等於[i-1][j-1]+1,
不同的情況下,二維數組的位置等於0,最後再查看二維數組的信息即可得到最長公共子串的長度,同時可以回溯二維數組得到最長公共字串的內容。
package other;
import util.ArrayUtil;
public class LongestCommonSubString {
public static void main(String[] args) {
longestCommonSubString("abcdefg","hbcsefgk");
}
public static void longestCommonSubString(String strX,String strY){
int pos_x = 0,pos_y = 0;
int lenX = strX.length();
int lenY = strY.length();
System.out.println("abcdef:"+lenX+";hbcsefgk:"+lenY);
int[][] L = new int[lenX+1][lenY+1];
int result = 0;
for(int i=1;i<=lenX;i++){
for(int j=1;j<=lenY;j++){
if(strX.charAt(i-1)==strY.charAt(j-1)){
L[i][j] = L[i-1][j-1]+1;
if (L[i][j] > result) {
result = L[i][j];
pos_x = i;// 記錄下最大長度在二維數組中的位置
pos_y = j;
}
}else{
L[i][j] = 0;
}
}
}
print(L);
System.out.println("最長公共子串 長度:"+result);
System.out.println("=============================");
// 輸出最長子串
StringBuilder sb = new StringBuilder();
while (L[pos_x][pos_y] != 0) {
sb.append(strX.charAt(pos_x - 1));
pos_x--;
pos_y--;
}
System.out.println(sb.reverse());
}
public static void print(int[][] arr){
for (int i = 0; i < arr[0].length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j][i]+" ");
}
System.out.println();
}
}
}