小明负责维护项目下的代码,需要查找出重复代码,用以支撑后续的代码优化,请你帮助小明找出重复的代码。
重复代码查找方法:以字符串形式给出两行代码(字符串长度1 < length <= 100
,由英文字母、数字和空格组成),找出两行代码中的最长公共子串。
注:如果不存在公共子串,返回空字符串。
输入的参数text1
、text2
分别代表两行代码。
输出任一最长公共子串。
输入:
hello123world
hello123abc4
输出:
hello123
输入:
private_void_method
public_void_method
输出:
_void_method
输入:
hiworld
hiweb
输出:
hiw
max_length
,并保存字符串的尾指针end
end
和最大长度max_length
,返回最长公共子串。def solve_method(text1, text2):
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
end = 0
max_length = 0
for i in range(1, len(text1) + 1):
for j in range(1, len(text2) + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
# 获取最大长度
if dp[i][j] > max_length:
max_length = dp[i][j]
end = i - 1
# 返回最长公共子串
return text1[end - max_length + 1: end + 1]
if __name__ == '__main__':
assert solve_method("hello123world", "hello123abc4") == "hello123"
assert solve_method("private_void_method", "public_void_method") == "_void_method"
assert solve_method("hiworld", "hiweb") == "hiw"