(美團網)兩個字串的最長公共子串

2021-06-26 03:02:53 字數 879 閱讀 8200

c[i][j]表示xi和yi的最大substring的長度,比如

x =

y =

c[1][1] = 1  

c[2][2] = 2  

c[3][3] = 0  

c[4][4] = 1

動態轉移方程為:

如果xi == yj, 則 c[i][j] = c[i-1][j-1]+1

如果xi ! = yj,  那麼c[i][j] = 0

最後求longest common substring的長度等於

max

#include "stdio.h"

#include "string.h"

#include "stdlib.h"

int longest_common_substring(char *str1, char *str2)

} }//輸出公共子串

char s[1000];

k=max;

i=x-1,j=y-1;

s[k--]='\0';

while(i>=0 && j>=0)

else //只要有乙個不相等,就說明相等的公共字元斷了,不連續了

break;

} printf("最長公共子串為:");

puts(s);

for(i = 0; i < len1+1; i++) //釋放動態申請的二維陣列

delete c[i];

delete c;

return max;

}int main(void)

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

問題 有兩個字串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...

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

求解兩個字串的最長公共子串 比如字串1 helloworld 字串2 hloop 則這兩個字串的最長公共子串行長度為2,最長公共子串行是 lo 問題定義 lcs i j 為以s1 i 與s2 j 為結尾的的最長公共子串的長度 遞推公式 lcs xn,ym lcs xn 1,ym 1 1 if x n...