[03]计算重复字符串长度-欢聚时代2018秋

1.题目描述

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

  • 输入描述:
    字符串,长度不超过 1000
  • 输出描述:
    重复子串的长度,不存在输出 0
  • 输入示例:
    ababcdabcefsgg
    
  • 输出示例:
    3
    
  • 说明:
    abc 为重复的最大子串,长度为 3

2.题目解析

[03]计算重复字符串长度-欢聚时代2018秋_第1张图片

3.参考答案

#include 
using namespace std;

int main(){
    string s;
    cin >> s;
    int res = 0;// 最大子串长度
    
    for(int i=0;i
#include 
#include 

using namespace std;

int statLen(string str, int i, int j) {
  int cur_len = 0;
  while (i < str.size() && j < str.size() && str[i] == str[j]) {// 判断子串
    i++;
    j++;
    cur_len++;
  }
  return cur_len;
}
int naiveLRS(string str) {
  int maxlen = 0;
  // 遍历所有字符串
  for (int i = 0; i != str.size(); ++i) {
    int len = 0;
    for (int j = i + 1; j != str.size(); j++) {
      len = statLen(str, i, j);// 获取子串长度
      if (maxlen < len) { // 记录最大长度
        maxlen = len;
      }
    }
  }
  return maxlen;
}
int main() {
  string str;
  cin >> str;
  printf("%d", naiveLRS(str));
}

牛客题目

你可能感兴趣的:([03]计算重复字符串长度-欢聚时代2018秋)