# LCS(Longest Common Substring)算法

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int lcs(const string, const string);
int max(int, int);

int main() {
//test
cout << lcs("qqqqaqaqqqaq", "zzzazazazz") << endl;
system("pause");
}

int lcs(const string a, const string b) {
vector<vector<int>> temp(a.size());
for (int i = 0; i < a.size(); i++) temp[i].resize(b.size());

for (int i = 0; i < a.size(); i++) {
if (a[i] == b[0] || i != 0 && temp[i - 1][0] == 1) temp[i][0] = 1;
else temp[i][0] = 0;
}
for (int j = 0; j < b.size(); j++) {
if (b[j] == a[0] || j != 0 && temp[0][j - 1] == 1) temp[0][j] = 1;
else temp[0][j] = 0;
}

for (int i = 1; i < a.size(); i++) {
for (int j = 1; j < b.size(); j++) {
if (a[i] == b[j]) temp[i][j] = 1 + temp[i - 1][j - 1];
else temp[i][j] = max(temp[i][j - 1], temp[i - 1][j]);
}
}

for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < b.size(); j++) {
cout << temp[i][j];
if (j != b.size()) cout << " ";
}
cout << endl;
}

return temp[a.size() - 1][b.size() - 1];
}

int max(int a, int b) { return a > b ? a : b; }

#### LCS（longest common subsequence）与LCS（longest common substring）以及后缀数组

2014-07-01 23:20:51

#### [SPOJ1811]LCS - Longest Common Substring

2016-04-04 12:42:30

#### 【后缀自动机】SPOJ(LCS2)[Longest Common Substring II]题解

2017-07-06 18:16:23

#### 常见算法问题之最长公共子串问题（Longest common substring problem）

2017-02-16 23:09:14

#### Longest Common Subsequence (LCS)最长公共子串

2015-07-01 14:31:21

#### LintCode之最长公共子串（Longest Common Substring）

2017-02-19 19:54:07

#### 【LeetCode】Longest Common Subsequence最长公共子序列（求出某一解+LCS长度） - Medium

2017-09-09 09:12:00

#### Longest Common Substring

2014-03-21 15:06:53

#### 【算法导论学习-29】动态规划经典问题02：最长公共子序列问题（Longest common subsequence，LCS）

2014-09-03 21:42:19

#### lintcode longest-common-subsequence 最长公共子序列 证明

2016-07-26 09:12:33