79 最長公共子串

2022-02-15 00:06:57 字數 906 閱讀 4545

中文english

給出兩個字串,找到最長公共子串,並返回其長度。

樣例 1:

輸入: "abcd" and "cbce"

輸出: 2

解釋:最長公共子串是 "bc"

樣例 2:

輸入: "abcd" and "eacb"

輸出: 1

解釋:

最長公共子串是 'a' 或 'c' 或 'b'

o(n x m) time and memory.

子串的字元應該連續的出現在原字串中,這與子串行有所不同。

輸入測試資料 (每行乙個引數)如何理解測試資料?

#最長公共子串

class

solution:

"""大致思路:

1. 依次切割b出來,切割成各個子串,然後在a中進行判斷,如果符合,則直接返回

"""def longestcommonsubstring(self, a, b):

# write your code here

if not a or not b:return

0l = len(a) if len(a) < len(b) else

len(b)

for index in range(l-1,-1,-1

): print(index,len(b) -index)

for i in range(len(b)-index):

cut_s = b[i:i + index + 1

] print(cut_s)

if cut_s in

a:

return len(cut_s)

79 最長公共子串

中等 最長公共子串 30 通過 給出兩個字串,找到最長公共子串,並返回其長度。您在真實的面試中是否遇到過這個題?yes 樣例給出a abcd b cbce 返回 2 注意子串的字元應該連續的出現在原字串中,這與子串行有所不同。include include includeint findthelon...

lintcode 79 最長公共子串

給出兩個字串,找到最長公共子串,並返回其長度。注意事項 子串的字元應該連續的出現在原字串中,這與子串行有所不同。樣例給出a abcd b cbce 返回 2 挑戰o n x m time and memory.標籤思路 參考部落格 與最長公共子串行相似,利用動態規劃,動態轉移方程為 codeclas...

最長公共子串行 最長公共子串

1 最長公共子串行 採用動態規劃的思想,用乙個陣列dp i j 記錄a字串中i 1位置到b字串中j 1位置的最長公共子串行,若a i 1 b j 1 那麼dp i j dp i 1 j 1 1,若不相同,那麼dp i j 就是dp i 1 j 和dp i j 1 中的較大者。class lcs el...