You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

最长围栏计数函数逻辑疑问:添加重复条件后结果为何正确?

为什么添加重复的最长值更新条件后,围栏长度计算函数结果正确?

你的测试用例|------|-|预期返回4,但错误实现返回2,核心问题在于错误代码只在连续序列被中断时才更新最长长度,完全漏掉了最长序列出现在字符串末尾的场景。

错误实现的核心缺陷

错误代码里,只有当相邻字符不匹配(进入else块)时,才会检查并更新longestFence。但如果最长的符合要求的连续序列刚好在字符串最后一段,循环结束前根本没有机会触发这个更新逻辑,导致最终返回的还是之前记录的较小值。

结合测试用例的执行流程具体看:

  1. 处理前半段|------:
    • 第一个|和-匹配(ASCII和为169),count变为2;
    • 下一个-和前一个-不匹配,进入else,把longestFence更新为2,count重置为1;
    • 后续的-之间都不匹配,每次进入else但count都是1,不会更新longestFence。
  2. 处理后半段|-|:
    • 从-和|匹配开始,count逐步增加到2、3、4;
    • 当循环执行到最后一次(i=9),count变为4后,i变成10,循环直接结束,错误实现里没有任何代码把这个count=4同步到longestFence里,所以最终返回的还是之前的2。

正确实现的修复逻辑

你在循环末尾添加的重复条件,本质是补上了“序列结束在字符串末尾”的场景处理:不管当前是延续序列(进入if块)还是中断序列(进入else块),每次循环结束后都检查一次count是否大于当前最长值,确保所有可能的最长序列都被记录下来。

在测试用例里,最后一次循环count变为4后,循环末尾的条件会把longestFence更新为4,所以最终返回正确结果。

错误实现代码

#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
}

正确实现代码

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.
}

内容的提问来源于stack exchange,提问作者Ziyad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:36:03