【发布时间】:2020-11-09 23:35:48
【问题描述】:
当我使用 for(i=0;i<strlen(s);i++) 时,我收到 time limit exceeded 错误。当我使用for(i=0;s[i]!='\0';i++) 我的代码得到successful 提交。为什么?
我还提供来自 codechef 的问题链接 - https://www.codechef.com/problems/LCPESY
类型 1:
for (i = 0; i < strlen(s1); i++) {
f1[s1[i]]++;
}
for (i = 0; i < strlen(s2); i++) {
f2[s2[i]]++;
}
类型 2:
for (i = 0; s1[i] != '\0'; i++) {
f1[s1[i]]++;
}
for (i = 0; s2[i] != '\0'; i++) {
f2[s2[i]]++;
}
完整代码:
#include <stdio.h>
#include <string.h>
long int min(long int a, long int b) {
if (a >= b)
return b;
else
return a;
}
int main(void) {
// your code goes here
int t;
scanf("%d", &t);
while (t--) {
char s1[10001], s2[10001];
scanf("%s%s", s1, s2);
long int f1[200] = { 0 }, f2[200] = { 0 }, i, count = 0;
for (i = 0; i < strlen(s1); i++) {
f1[s1[i]]++;
}
for (i = 0; i < strlen(s2); i++) {
f2[s2[i]]++;
}
for (i = 0; i < 200; i++) {
count += min(f1[i], f2[i]);
}
printf("%ld\n", count);
}
return 0;
}
【问题讨论】:
-
因为
strlen被实现为一个看起来像“Type-2”中的循环的循环。因此,如果字符串有 100 个字符,“Type-2”在找到\0之前会比较 100 个字符,但“Type-1”会比较 10000 个字符来查找\0100 次。要修复“Type-1”,您应该在循环之前调用strlen一次,并将长度保存在变量中。 -
strlen()在循环中每次被评估一次;一个聪明的编译器可以将函数移出循环......但如果你尝试unsigned limit = strlen(s); for (i = 0; i < limit; i++) { ... }它可能会被接受。 -
这两个循环不一定等价,例如
s在循环内被修改。 -
@pmg 谢谢。我已经尝试过你的方法并且它有效。但是为什么 strlen() 每次都通过循环进行评估,我不明白。
-
一个
for循环基本上由4部分组成:初始化、条件、增量和主体(for (<increment>; <condition>; <increment>) { <body> })。除了只执行一次的<initialization>,所有部分每次“for执行”时都执行一次,而有问题的strlen()是<condition>语句的一部分.. 即for循环运行如下:<initialization>/<condition>/<body>/<increment>/<condition>/<body>/<increment>/<condition>/<body>/<increment>s/<increment>s/<increment>/@9876434 >
标签: arrays c string algorithm runtimeexception