查找最长字符串并记录个数

整理笔记时突然看到以前帮群里伙伴解决的一道算法题,还是放博客上来吧

这里写图片描述

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值