截图来自https://www.cnblogs.com/coderJiebao/p/Algorithmofnotes30.html
#pragma once
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const unsigned int MAXSIZE = 101;
class LSS
{
public:
LSS(){}
LSS(string s):m_str(s){
init();
}
~LSS(){}
void init() {
int len = m_str.size();
for (int i = 0; i < len; i++) {
m_LSSArr[i][i] = true;
if(i+1<len)
m_LSSArr[i][i + 1] = (m_str.at(i) == m_str.at(i + 1));
}
getLSSArr();
}
void getLSSArr() {
int len = m_str.size();
for (int direct = 2; direct < len; direct++)
for (int last = direct, first = 0; last < len&&first < len; last++, first++) {
if (m_str.at(first) == m_str.at(last)) {
m_LSSArr[first][last] = m_LSSArr[first + 1][last - 1];
}
else {
m_LSSArr[first][last] = false;
}
}
}
void getLongestSS() {
int len = m_str.size();
bool isGetAll = false;
vector<pair<int, int> > vecLss;
for (int direct = len - 1; direct >= 0; direct--) {
for (int last = direct, first = 0;
last < len&&first < len; last++, first++) {
if (m_LSSArr[first][last]) {
vecLss.push_back(make_pair(first, last));
isGetAll = true;
}
}
if (isGetAll) break;
}
for(pair<int,int> t:vecLss) showLSStr(t);
}
void showLSStr(const pair<int, int> p) {
string strAns = m_str.substr(p.first, p.second - p.first + 1);
cout << strAns
<< " length: " << strAns.size()
<< endl;
}
private:
string m_str;
bool m_LSSArr[MAXSIZE][MAXSIZE];
};
void testForLSS() {
string s = "silliss fllif",ss="SDSFSDSDDD";
LSS test(s);
test.getLongestSS();
}
注意到:
1)不要越界
if(i+1<len)
m_LSSArr[i][i + 1] = (m_str.at(i) == m_str.at(i + 1));
2)外层方向与左上到右下
for(int direct=2; direct<len;direct++)
for (int last = direct,first = 0;
last < len&&first<len;
last++,first++)
3)注意测试小函数
/*
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
cout << m_LSSArr[i][j] << " ";
}
cout << endl;
}
*/