給兩個字符串,求兩個字符串的最長子串
(例如:“abc”“xyz”的最長子串為空字符串,“abcde”和“bcde”的最長子串為“bcde”)
解題思路:
- 把兩個字符串分成一個行列的二維矩陣
- 比較二維矩陣中每個點對應行列字符中否相等,相等的話值設置為1,否則設置為0。
- 通過查找出值為1的最長對角線就能找到最長公共子串。
從圖中我們可以看到,等於1的那個對角線就是我們要求的最長公共子串,同時我們還可以再優化一下:
剛才我們說“比較二維矩陣中每個點對應行列字符中否相等,相等的話值設置為1,否則設置為0。” ,那么我們並不需要一直等於1,即:兩個值相等時(a[i]b[j]),我們判斷對角線前一個值是否相等(a[i-1]b[j-1]), 如果相等,那么我們只需要加上前一個的值即可。
我們可以通過一個二維數組實現:
int[][] arr = new int [a.length()][b.length()];
if (a.substring(i,i+1).equals(b.substring(j,j+1))){
arr[i][j] = 1+ arr[i-1][j-1] ;
}
完整代碼為:
public class Lcs {
public static String lCs(String a,String b){
int[][] arr = new int [a.length()][b.length()];
int leng = 0;
int index = 0;
for (int i=0;i<a.length();i++){
for (int j=0;j<b.length();j++){
if (a.substring(i,i+1).equals(b.substring(j,j+1))){
if (i>0 && j>0){
arr[i][j] = 1+ arr[i-1][j-1] ;
}else{
arr[i][j] = 1;
}
}else {
arr[i][j] = 0;
}
if (arr[i][j]>leng){
leng=arr[i][j];
index = i ;
}
}
}
return a.substring(index-leng+1,index+1);
}
public static void main(String[] args) {
System.out.println(Lcs.lCs("abcdefghij","asdabchij"));
}
}
[post url="https://github.com/CoderXiaohui/LeetCode/blob/master/src/String/Lcs.java" title="GitHub" intro="GitHub" cover="https://github.com/fluidicon.png" /]