赞
踩
目录
求最大公共子串,使用递推实现 假设 x(i):字符串第i个字符 y(j):字符串第j个字符 dp[i][j]:以x(i),y(j)结尾的最大子串长度。比如:x: "abcde" y:"bcdae" dp[2][1]:以x(2),y(1)结尾的最大子串长度即:x遍历到"abc",y遍历 到"bc",都以字符'c'结尾时最大公共子串为"bc" 。故:当计算dp[i][j]时,首先看x(i),y(j)的值:
- #include <iostream>
- using namespace std;
- int main()
- {
- string str1 = "", str2 = "";
- cin >> str1 >> str2;
- int n1 = str1.size(), n2 = str2.size();
- int res = -1;
- for (int i = 0; i < n1; ++i)
- {
- for (int j = 0; j < n2; ++j)
- {
- int cnt = 0;
- int tmpi = i, tmpj = j;
- while (tmpi < n1 && tmpj < n2 && str1[tmpi++] == str2[tmpj++])
- {
- ++cnt;
- }
- res = max(res, cnt);
- }
- }
- cout << res << endl;
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。