输入两个字符串,要求输出最长的公共子串。
时间: 2023-10-09 13:09:39 浏览: 125
好的,您可以使用动态规划的思想来解决这个问题。定义一个二维数组dp[i][j]表示以第一个字符串中第i个字符和第二个字符串中第j个字符结尾的最长子串的长度。则有如下状态转移方程:
如果第一个字符串中第i个字符和第二个字符串中第j个字符相等,则dp[i][j]=dp[i-1][j-1]+1。
如果第一个字符串中第i个字符和第二个字符串中第j个字符不相等,则dp[i][j]=0。
最后遍历二维数组dp,找到其中最大的值,即为最长公共子串的长度。同时通过找到最大值时的i和j,可以确定最长公共子串的具体内容。
需要注意的是,这种方法的时间复杂度是O(mn),其中m和n分别为两个字符串的长度。如果想要进一步优化算法,可以使用后缀数组(suffix array)等高级数据结构。
相关问题
求两个字符串的最长公共子串。 要求:输入两个字符串,输出它们的最长公共子串,包括长度。 设计一个类String,包括一个len(字符串长度)和字符串指针s。
可以使用动态规划来解决这个问题。具体而言,我们可以定义一个二维数组dp,其中dp[i][j]表示以第一个字符串的第i个字符和第二个字符串的第j个字符为结尾的最长公共子串的长度。对于任意的i和j,如果第一个字符串的第i个字符和第二个字符串的第j个字符相同,那么我们有dp[i][j] = dp[i-1][j-1]+1,否则dp[i][j] = 0。最终的答案即为所有dp[i][j]中的最大值。
以下是代码实现:
```
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
int len;
char* s;
String() {}
String(const char* str) {
len = strlen(str);
s = new char[len];
strcpy(s, str);
}
~String() {
if (s != nullptr) {
delete[] s;
}
}
};
void longestCommonSubstring(String& s1, String& s2) {
int** dp = new int*[s1.len + 1];
for (int i = 0; i <= s1.len; i++) {
dp[i] = new int[s2.len + 1];
memset(dp[i], 0, (s2.len + 1) * sizeof(int));
}
int maxLen = 0;
int endIndex = -1;
for (int i = 1; i <= s1.len; i++) {
for (int j = 1; j <= s2.len; j++) {
if (s1.s[i - 1] == s2.s[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
endIndex = i - 1;
}
}
}
}
if (endIndex == -1) {
cout << "没有公共子串" << endl;
} else {
cout << "最长公共子串为:" << endl;
for (int i = endIndex - maxLen + 1; i <= endIndex; i++) {
cout << s1.s[i];
}
cout << endl;
cout << "长度为:" << maxLen << endl;
}
for (int i = 0; i <= s1.len; i++) {
delete[] dp[i];
}
delete[] dp;
}
int main() {
String s1("abcdefg");
String s2("bcdefgh");
longestCommonSubstring(s1, s2);
return 0;
}
```
上述代码的输出结果为:
```
最长公共子串为:
bcdefg
长度为:6
```
设计一函数找出两个字符串中的最大公共子串。并利用此函数从键盘输入两个字符串, 输出这两个字符串的最大公共子串
设计一个名为`find_longest_common_substring`的函数,可以采用动态规划(Dynamic Programming)的方法来解决这个问题。这种算法通过创建一个二维数组记录每个位置上子串的最大公共长度,然后回溯找到最长的公共子串。
```python
def find_longest_common_substring(s1, s2):
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_len = 0
end_index = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
if dp[i][j] > max_len:
max_len = dp[i][j]
end_index = i - 1
else:
dp[i][j] = 0
return s1[end_index - max_len + 1:end_index + 1]
# 输入示例
s1 = input("请输入第一个字符串: ")
s2 = input("请输入第二个字符串: ")
result = find_longest_common_substring(s1, s2)
print(f"这两个字符串的最大公共子串是: {result}")
阅读全文
相关推荐








