求兩個字串的最長公共子串

2022-05-07 00:45:17 字數 1324 閱讀 3752

採用乙個二維矩陣來記錄中間結果,矩陣的橫座標為字串1的各個字元,矩陣的縱座標為字串2的各個字元。

舉例說明:假設兩個字串分別為"bab"和"caba" (當然我們現在一眼就可以看出來最長公共子串是"ba"或"ab")

b  a  b

c  0  0  0

a  0  1  0

b  1  0  1

a  0  1  0

可以看出,矩陣的斜對角線最長的那個就對應著兩個字串的最長公共子串。

不過在二維矩陣上找最長的由1組成的斜對角線也是件麻煩費時的事,可以用下面的方法改進:當要在矩陣是填1時讓它等於其左上角元素加1。

b  a  b

c  0  0  0

a  0  1  0

b  1  0  2

a  0  2  0

這樣矩陣中的最大元素就是最長公共子串的長度。另外,在構造這個二維矩陣的過程中由於得出矩陣的某一行後其上一行就沒用了,所以實際上在程式中可以用一維陣列來代替這個矩陣。

**:

public

class

solution

if(strone.equals("") || strtwo.equals(""))

//矩陣的橫向長度

int len1 =strone.length();

//矩陣的縱向長度

int len2 =strtwo.length();

//儲存矩陣的上一行

int topline = new

int[len1];

//儲存矩陣的當前行

int currentline = new

int[len1];

//矩陣元素中的最大值

int maxlen = 0;

//矩陣元素最大值出現在第幾列

int pos = 0;

char ch = ' ';

for(int i=0; i)

else

if(currentline[j] >maxlen)}}

//將矩陣的當前行元素賦值給topline陣列; 並清空currentline陣列

for(int k=0; k)

//或者採用下面的方法

//topline = currentline;

//currentline = new int[len1];

}

return strone.substring(pos-maxlen+1, pos+1);

}public

static

void

main(string args)

}

求兩個字串的最長公共子串

問題 有兩個字串str和str2,求出兩個字串中最長公共子串長度。比如 str acbcbcef,str2 abcbced,則str和str2的最長公共子串為bcbce,最長公共子串長度為5。演算法思路 1 把兩個字串分別以行和列組成乙個二維矩陣。2 比較二維矩陣中每個點對應行列字元中否相等,相等的...

求兩個字串的最長公共子串

def longestcommonsequence str one,str two,case sensitive true str one 和 str two 的最長公共子串行 param str one 字串1 param str two 字串2 正確結果 param case sensitive...

求兩個字串的最長公共子串

直接上 需要使用時直接呼叫即可。求字串的最長公共子串 public class maxstringdemo public static intset string aa,string bb public static stringbuilder maxutil2 string str1,string...