目录
解法:
牛客网-C++校招面试题合集 143
// 143_最长公共连续子序列.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int substr(string &str1,string &str2)
{
int len1 = str1.length();
int len2 = str2.length();
vector<vector<int>> dp(len1, vector<int>(len2, 0));
int longest = 0;
int longest_index = 0;
for (int i = 0; i < len1; i++)
{
dp[i][0] = str1[i] == str1[0] ? 1 : 0;
if (longest < dp[i][0])
{
longest = dp[i][0];
longest_index = i;
}
}
for (int j = 0; j < len2; j++)
{
dp[0][j] = str1[0] == str2[j] ? 1 : 0;
if (longest < dp[0][j])
{
longest = dp[0][j];
longest_index = 0;
}
}
for (int i = 1; i < len1; i++)
{
for (int j = 1; j < len2; j++)
{
if (str1[i] == str2[j])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
if (longest < dp[i][j])
{
longest = dp[i][j];
longest_index = i;
}
}
}
for (int i = longest_index - longest + 1; i <= longest_index; i++)
{
cout << str1[i];
}
cout << endl;
return longest;
}
int main()
{
string str1 = "abeabde";
string str2 = "abecdef";
substr(str1, str2);
return 0;
}
KMP算法
Manacher算法
参考文献: