整理笔记时突然看到以前帮群里伙伴解决的一道算法题,还是放博客上来吧
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct Mydata
{
string maxstr;
int number;
}Listdate;
class Isfind
{
public:
Isfind(const std::string &str) :m_string(str){}
bool operator ()(const vector<Listdate>::value_type &cstr)
{
return cstr.maxstr == m_string;
}
private:
const string &m_string;
};
void showdata(const vector<Listdate> myshow)
{
for (auto val : myshow)
{
cout << val.maxstr << " :" << val.number << " ";
}
cout << endl;
}
void FindStr(const string &str)
{
string temp;
vector<Listdate> maxstr;
bool oldmax = true;
int MaxLen = 0;
for (int i = 0; i < str.length(); ++i)
{
for (int j = str.length() - i; j != 0; --j)
{
temp = str.substr(i, j);//从i开始,长度为j的字符串
int front = str.find(temp);
int behind = str.rfind(temp);
int templen = temp.length();
Listdate newdate;
if (front != behind&&templen > MaxLen)
{
newdate.maxstr = temp;
newdate.number = 1;//按理说找到第一个时候,字符串个数应该是2,但是因为找到最有一个最长子字符串时,又会多计数一次,所以这里赋值为1.
MaxLen = templen;
maxstr.clear();
maxstr.push_back(newdate);
oldmax = false;
}
if (front != behind && templen == MaxLen && oldmax)
{
auto index = find_if(maxstr.begin(), maxstr.end(), Isfind(temp));
if (index == maxstr.end())
{
newdate.maxstr = temp;
newdate.number = 1;
maxstr.push_back(newdate);
}
else
{
++((*index).number);
}
}
oldmax = true;
}
}
showdata(maxstr);
return;
}
int main(void)
{
//string str1 = "555512355551235555545";
string str2 = "123123";
//FindStr(str1);
FindStr(str2);
return 0;
}