gpt4 book ai didi

c - 为什么我在这个问题上得到了错误的答案(Uva OJ 455)

转载 作者:行者123 更新时间:2023-11-30 19:27:03 27 4
gpt4 key购买 nike

我很喜欢this problem (乌瓦455):

A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k. For example, the string ”abcabcabcabc” has period 3, since it is formed by 4 repetitions of the string ”abc”. It also has periods 6 (two repetitions of ”abcabc”) and 12 (one repetition of ”abcabcabcabc”).

Write a program to read a character string and determine its smallest period.

Input

The first line oif the input file will contain a single integer N indicating how many test case that your program will test followed by a blank line. Each test case will contain a single character string of up to 80 non-blank characters. Two consecutive input will separated by a blank line.

Output

An integer denoting the smallest period of the input string for each input. Two consecutive output are separated by a blank line.

Sample Input

1

HoHoHo

Sample Output

2

我已经检查了我能想象到的所有测试用例,并且所有测试用例都返回了正确的结果,但我仍然在在线判断中得到错误的答案。我哪里做错了?(英语不是我的母语;请原谅打字或语法错误。)

#include <stdio.h>
#include <string.h>
#define maxn 85

int check(char* s, int per){
for(int i = 0; i < strlen(s) - per; i++){
if(s[i + per] != s[i]) return 0;
}
return 1;
}

int main(){
int T;
scanf("%d", &T);
char s[maxn];
while(T--){
scanf("%s", s);
int len = strlen(s);
bool OK = false;
for(int i = 1; i <= len/2 && (len % i == 0); i++){//That's wrong.
if(check(s, i)){
printf("%d\n", i);
OK = true;
break;
}
}
if(!OK) printf("%d\n", len);
if(T) printf("\n");
}
return 0;
}

最佳答案

问题出在 for(int i = 1; i <= len/2 && (len % i == 0); i++) 。一遇到i就停下来不能除len ,而不是跳过它。

将循环写为:

for (int i = 1; i <= len/2; i++) {
if (len % i != 0) continue;

...
}

关于c - 为什么我在这个问题上得到了错误的答案(Uva OJ 455),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203786/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com