OR80. 计算重复字符串长度
描述
请从字符串中找出至少重复一次的子字符串的最大长度输入描述
字符串,长度不超过1000输出描述
重复子串的长度,不存在输出0示例1
输入:
ababcdabcefsgg
输出:
3
说明:
abc为重复的最大子串,长度为3C++14 解法, 执行用时: 1ms, 内存消耗: 372KB, 提交时间: 2020-08-21
#include<stdio.h> #include<string.h> int main() { char str[1024]; scanf("%s",str); int len = strlen(str); int count = 0, max = 0; int offset = 1; while(len - offset >= max) { for(int i = 0;i < len - offset;i++) { if(str[i] == str[i + offset]) count++; else { if(count > max) max = count; count = 0; } } offset++; } if(count > max) max = count; printf("%d",max); return 0; }
C 解法, 执行用时: 1ms, 内存消耗: 372KB, 提交时间: 2020-07-16
#include <stdio.h> #include <string.h> #include <stdbool.h> #define max(a, b) ((a) > (b) ? (a) : (b)) char* substr(char *str, int left, int right) { char *res = (char *) malloc((right - left + 1) * sizeof(char)); for (int i = left; i < right; ++i) { res[i - left] = str[i]; } res[right - left] = '\0'; return res; } bool find(char *str, char *sub) { for (int i = 0; i < strlen(str); ++i) { if (strncmp(str + i, sub, strlen(sub)) == 0) { return true; } } return false; } int main() { char str[1001]; scanf("%s", str); int maxlen = 0; int left, right; left = 0; right = 1; while (left <= right && right < strlen(str)) { char *s = substr(str, left, right); if (find(str + right, s)) { maxlen = max(maxlen, right - left); ++right; } else { ++left; if (left >= right) { ++right; } } free(s); } printf("%d\n", maxlen); return 0; }