问题:字符串 "ABABC", "BABCA" 最长公共子字符串是 "ABC"?
solution1: suffix tree
建立suffix tree时间复杂度是O(N), 查找公共子字符串的代价是O(m+n), m和n分别是两个字符串的长度。
关于suffix tree请参考http://mila.cs.technion.ac.il/~yona/suffix_tree/
solution2:Dynamic Programming
对于字符串"ABAB", "BABA"
A | B | A | B | ||
---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | |
B | 0 | 0 | 1 | 0 | 1 |
A | 0 | 1 | 0 | 2 | 0 |
B | 0 | 0 | 2 | 0 | 3 |
A | 0 | 1 | 0 | 3 | 0 |