首页 > 试题广场 >

Coincidence

[编程题]Coincidence
  • 热度指数:10559 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
Find a longest common subsequence of two strings.

输入描述:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.


输出描述:
For each case, output k – the length of a longest common subsequence in one line.
示例1

输入

abcd
cxbydz

输出

2
while True:
    try:
        string1,string2 = input(),input()
        result = [[0 for i in range(len(string2)+1)] for j in range(len(string1)+1)]
        #result[i][j]保存string1前i个子串和string2前j个子串的公共子序列
        for i in range(1,len(string1)+1):
            for j in range(1,len(string2)+1):
                result[i][j] = max(result[i-1][j],result[i][j-1])
                if string1[i-1]==string2[j-1]:
                    result[i][j] = result[i-1][j-1]+1    #等于子串都减一的公共子序列长度加一
        print(result[-1][-1])
    except Exception:
        break
编辑于 2018-10-12 09:29:32 回复(0)