解题思路
-
题目要求:
- 计算两个字符串的最长公共子串长度
- 子串必须连续
- 只包含小写字母
- 字符串长度:
-
解题方法:动态规划
- 使用二维dp数组记录公共子串长度
表示以
和
结尾的最长公共子串长度
- 如果当前字符相同,则
代码
def longest_common_substring(str1, str2):
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_len = 0
# 填充dp数组
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
max_len = max(max_len, dp[i][j])
return max_len
while True:
try:
str1 = input().strip()
str2 = input().strip()
print(longest_common_substring(str1, str2))
except:
break
import java.util.*;
public class Main {
public static int longestCommonSubstring(String str1, String str2) {
int m = str1.length(), n = str2.length();
int[][] dp = new int[m + 1][n + 1];
int maxLen = 0;
// 填充dp数组
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1.charAt(i-1) == str2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + 1;
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
return maxLen;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str1 = sc.nextLine();
String str2 = sc.nextLine();
System.out.println(longestCommonSubstring(str1, str2));
}
}
}
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int longestCommonSubstring(string str1, string str2) {
int m = str1.length(), n = str2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
int maxLen = 0;
// 填充dp数组
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1[i-1] == str2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
maxLen = max(maxLen, dp[i][j]);
}
}
}
return maxLen;
}
int main() {
string str1, str2;
while (getline(cin, str1) && getline(cin, str2)) {
cout << longestCommonSubstring(str1, str2) << endl;
}
return 0;
}
算法分析
- 算法:动态规划
- 时间复杂度:
,其中
和
是两个字符串的长度
- 空间复杂度:
,需要二维dp数组