Lintcode(5)-最长公共子串
来源:互联网 发布:少女淘宝店铺推荐 编辑:程序博客网 时间:2024/05/22 12:06
Q:
给出两个字符串,找到最长公共子串,并返回其长度。
给出A=“ABCD”,B=“CBCE”,返回 2
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
A:
可以使用动态规划让时间复杂度降至O(n²)
关于动态规划这篇文章写得很好很强大!
这里使用最原始的办法,时间复杂度O(n³)
class Solution {public: /** * @param A, B: Two string. * @return: the length of the longest common substring. */ int longestCommonSubstring(string &A, string &B) { std::size_t a_len = A.length(); std::size_t b_len = B.length(); if (!a_len || !b_len) { return 0; } std::size_t a_start = std::string::npos; std::size_t b_start = std::string::npos; std::size_t longest = 0; for (std::size_t i = 0; i < a_len; ++i) { for (std::size_t j = 0; j < b_len; ++j) { std::size_t this_l = 0; std::size_t this_i = i; std::size_t this_j = j; for (; this_i < a_len && this_j < b_len; this_i++, this_j++) { if (A[this_i] == B[this_j]) this_l++; else break; } if (this_l > longest) { longest = this_l; a_start = this_i; b_start = this_j; } } } return longest; }};
0 0
- Lintcode(5)-最长公共子串
- LintCode-最长公共子串
- LintCode 最长公共子串
- LintCode : 最长公共子串
- LintCode : 最长公共子串
- LintCode 最长公共子串
- 最长公共子串-LintCode
- lintcode -- 最长公共子串
- Lintcode—(5)最长公共子串
- lintcode-最长公共子串-79
- lintcode 求最长公共子串
- lintcode 之 最长公共子串
- LintCode 79 最长公共子串
- LintCode : 最长公共子序列
- LintCode 最长公共子序列
- 最长公共子序列-LintCode
- lintcode--最长公共子序列
- [Lintcode]Longest Common Substring最长公共子串
- 游戏设计的艺术:一本透镜的书——第七章 游戏通过迭代改良
- CSRF 跨站点请求伪造
- HttpURLConnection的流式输出的缺陷和解决方法
- 关于WM_MOUSEHOVER和WM_MOUSELEAVE消息的用法以及按钮的变色问题!
- linux 安装php 不安装mysql 需要支持mysql mysqli mysql-pdo
- Lintcode(5)-最长公共子串
- 您尝试打开的文件XXX.xls的格式与文件扩展名制定的格式不一致
- 显卡 : 什么是渲染管线
- 一个简单的带游标的存储过程
- Spring监管下的Hibernate配置文件
- 游戏设计的艺术:一本透镜的书——第八章 游戏是为玩家做的
- JS 身份证号校验 年龄校验
- Eas Bos 如何往kdlabel载入自己的图片
- 菲律宾副总统与阿基诺彻底闹掰 国内一片大乱