LintCode: Longest Common Substring
2015-12-01 12:18
295 查看
C++
暴力搜索
两个游标一个长度
i遍历a
j遍历b
len遍历公共子串长度
C++,
dp
暴力搜索
两个游标一个长度
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; } };
相关文章推荐
- PS自动生成不同尺寸图标
- 关于android5.1 strings product值引起的复写字串不起效问题的解决方法
- POJ 1664 放苹果
- ZOJ - 2112 Dynamic Rankings(BIT套主席树)
- PhpStorm WebMatrix xDebug 配置开发环境
- 权限之路径拦截
- hough变换是如何检测出直线和圆的?
- FastReport经验
- Oracle修改表结构字段名和字段长度
- Oracle单组函数
- PHP接收json 并将接收数据插入数据库的实现代码
- linux下软链接和硬链接的区别 【转】
- 可扩展机器学习——概述
- leetcode ugly number 2
- android 获得屏幕状态
- 单位和尺寸
- linux下VI模式中上下左右键和回退键出现字母
- hdu3949
- 【非技术】谈谈简历那些事儿
- AppleWatch___学习笔记(三)iPhone和Apple Watch上的数据同步