您的位置:首页 > 其它

LintCode: Longest Common Substring

2015-12-01 12:18 295 查看
C++

暴力搜索

两个游标一个长度

i遍历a

j遍历b

len遍历公共子串长度

class Solution {
public:
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
int m = A.size();
int n = B.size();
if (m == 0 || n == 0) {
return 0;
}
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int len = 0;
while (i + len < m && j + len < n && A[i + len] == B[j + len]) {
len ++;
ans = max(ans, len);
}
}
}
return ans;
}
};


C++,

dp

class Solution {
public:
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
int m = A.size();
int n = B.size();
if (m == 0 || n == 0) {
return 0;
}
vector<vector <int> > dp(m + 1, vector<int>(n + 1));
// int[][] dp = new int[m + 1][n + 1];
int ans = 0;
for (int i = 0; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else {
if (A[i-1] == B[j-1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
ans = max(dp[i][j], ans);
} else {
dp[i][j] = 0;
}
}
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: