欢聚时代校招编程题计算重复字符串的长度

题目描述

请从字符串中找出至少重复一次的子字符串的最大长度

输入描述:

字符串,长度不超过1000

输出描述:

重复子串的长度,不存在输出0

示例1

输入

ababcdabcefsgg

输出

3

说明

abc为重复的最大子串,长度为3

这道题目使用穷举子串Map的方法,时间复杂度是O(N^2)

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
    string str;
    cin>>str;
    map<string,int> mp;
    int n = str.size();
    for(int j=0;j<n;j++){
        for(int i=0;i<=j;i++){
            mp[str.substr(i,j-i+1)]++;
        }
    }
    int max = 0;
    for(auto it=mp.begin();it!=mp.end();++it){
        if(it->second>1 && it->first.size()>max){
            max = it->first.size();
        }
    }
    cout<<max<<endl;
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/89739534