Skip to content

Commit 5c2cf8e

Browse files
committed
add Longest Common Substring
1 parent 2717a9d commit 5c2cf8e

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
* [Two Strings Are Anagrams](string/two_strings_are_anagrams.md)
4040
* [Compare Strings](string/compare_strings.md)
4141
* [Anagrams](string/anagrams.md)
42+
* [Longest Common Substring](string/longest_common_substring.md)
4243
* [Linked List - 链表](linked_list/README.md)
4344
* [Remove Duplicates from Sorted List](linked_list/remove_duplicates_from_sorted_list.md)
4445
* [Remove Duplicates from Sorted List II](linked_list/remove_duplicates_from_sorted_list_ii.md)

string/longest_common_substring.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Longest Common Substring
2+
3+
## Source
4+
5+
- lintcode: [(79) Longest Common Substring](http://www.lintcode.com/en/problem/longest-common-substring/)
6+
7+
```
8+
Given two strings, find the longest common substring.
9+
Return the length of it.
10+
11+
Example
12+
Given A="ABCD", B="CBCE", return 2.
13+
Note
14+
The characters in substring should occur continuously in original string.
15+
This is different with subsequence.
16+
```
17+
18+
## 题解
19+
20+
求最长公共子串,注意「子串」和「子序列」的区别!简单考虑可以使用两根指针索引分别指向两个字符串的当前遍历位置,若遇到相等的字符时则同时向后移动一位。
21+
22+
### C++
23+
24+
```c++
25+
class Solution {
26+
public:
27+
/**
28+
* @param A, B: Two string.
29+
* @return: the length of the longest common substring.
30+
*/
31+
int longestCommonSubstring(string &A, string &B) {
32+
if (A.empty() || B.empty()) {
33+
return 0;
34+
}
35+
36+
int lcs = 0, lcs_temp = 0;
37+
for (int i = 0; i < A.size(); ++i) {
38+
for (int j = 0; j < B.size(); ++j) {
39+
lcs_temp = 0;
40+
while ((i + lcs_temp < A.size()) &&\
41+
(j + lcs_temp < B.size()) &&\
42+
(A[i + lcs_temp] == B[j + lcs_temp]))
43+
{
44+
++lcs_temp;
45+
}
46+
47+
// update lcs
48+
if (lcs_temp > lcs) {
49+
lcs = lcs_temp;
50+
}
51+
}
52+
}
53+
54+
return lcs;
55+
}
56+
};
57+
```
58+
59+
### 源码分析
60+
61+
1. 异常处理,空串时返回0.
62+
2. 分别使用`i``j`表示当前遍历的索引处。若当前字符相同时则共同往后移动一位。
63+
3. 没有相同字符时比较此次遍历的`lcs_temp``lcs`大小,更新`lcs`.
64+
4. 返回`lcs`.
65+
66+
注意在`while`循环中不可直接使用`++i`或者`++j`,因为有可能会漏解!
67+
68+
### 复杂度分析
69+
70+
双重 for 循环,最坏时间复杂度约为 $$O(mn \cdot lcs)$$.
71+
72+
## Reference
73+
74+
- [Longest Common Substring | 九章算法](http://www.jiuzhang.com/solutions/longest-common-substring/)

0 commit comments

Comments
 (0)