我有一个活动:
让我们考虑以下测试用例:
|------|-|
^^^^ 4
我认为它应该返回 4,但实际上它返回 2。
不正确的尝试:(底部调用者)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
//Prototypes:
int longestFence(char input[], int size);
int main (void)
{
char fenceString[] = "|------|-|"; // size is 10
printf("%s → %d", fenceString, longestFence(fenceString, 10));
}
int longestFence (char input[], int size)
{
int longestFence = 1; //Assume the lowest length (similar to Max activity)
int count = 1;
for (int i = 1; i < size;) //Start comparing from second index
{
if (input[i] + input[i - 1] == 169) //Compare each index with the previous index
{
count++;
i++;
}
else
{
if (count > longestFence)
longestFence = count;
count = 1; //reset counting
i++;
}
}
return longestFence; // It should return 4 not 2
}
我修改了该函数,将 else 内部的条件也添加到 else 的外部,现在它按预期工作并返回 4,但是如何呢?我无法理解这种修改背后的逻辑...
工作尝试:
int longestFence (char input[], int size)
{
int longestFence = 1; //Assume the lowest length (similar to Max activity)
int count = 1;
for (int i = 1; i < size;) //Start comparing from second index
{
if (input[i] + input[i - 1] == 169) //Compare each index with the previous index
{
count++;
i++;
}
else
{
if (count > longestFence) //repeat this condition outside of else
longestFence = count;
count = 1; //reset counting
i++;
}
//FIX :
//The condition is repeated, now it's solved!
if (count > longestFence)
longestFence = count;
}
return longestFence; // It returns 4 as it should.
}
要调试此问题,您应该在纸上或其他地方绘制出变量随时间变化的状态。
您会发现您从未设置
longestFence
if 对于在字符串末尾找到的栅栏。
第二个片段起作用的原因不是你检查了两次;而是你检查了两次。而是您在不同的位置进行了检查。
实际的修复是这样的:
if (input[i] + input[i - 1] == 169)
{
count++;
// HERE
if (count > longestFence)
longestFence = count;
}
else
{
count = 1; //reset counting
// NOT HERE.
}
// COULD BE HERE INSTEAD, BUT NOT BEST
您的代码有第二个错误:它返回
1
表示空字符串。
我会怎么写:
size_t longestFence( const char *s ) {
size_t max = 0;
size_t len = 0;
char prev = 0;
for ( ; *s; ++s ) {
if ( *s != prev ) {
prev = *s;
++len;
if ( max < len )
max = len;
} else {
len = 1;
}
}
return max;
}