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

Codility短信拆分问题:代码仅通过5/8测试用例,求问题排查

Codility短信拆分挑战代码问题排查

问题背景

我正在解决Codility的短信拆分挑战:需将符合规则的文本拆分为单条最多K字符的短信,不可拆分单词,要求短信数量最少,若单个单词长度超过K则返回-1。编写的Java代码本地测试所有自拟用例均通过,但在Codility平台仅通过5/8测试用例,希望找出代码中的遗漏点。

挑战详情

输入文本由大小写字母和空格组成,无首尾空格及连续空格;需实现函数public static int solution(String S, int K)返回短信数。示例:输入S="SMS messages are really short"、K=12时,应返回3。

我的代码

public static int solution (String S, int K) {
    String[] words = S.split(" ");
    StringBuilder sb = new StringBuilder();
    String currentWord = "";
    int linesCount = 1;
    boolean isFirst = true;

    for (String word: words) {
        if (word.length() > K) {
            return -1;
        }
    }

    for (String word: words) {
        if (currentWord.length() + word.length() + 1 > K) {
            sb.append(currentWord).append("\n");
            linesCount++;
            currentWord = word;
        } else {
            if (isFirst) {
                currentWord += word;
                isFirst = false;
            } else {
                currentWord += " " + word;
            }
        }
    }
    sb.append(currentWord);
    System.out.println(sb.toString());

    return linesCount;
}

代码遗漏点及修正方案

核心问题1:初始状态的空格计算错误

当第一条短信还未添加任何单词时,currentWord为空字符串,此时判断currentWord.length() + word.length() + 1 > K会错误地多计算一个空格的长度。例如当第一个单词长度恰好等于K时,该条件会判定0 + K + 1 > K成立,触发换行逻辑,导致短信计数错误加1,且第一条短信内容为空(实际应直接放入该单词)。

核心问题2:空输入处理缺失

若输入S为空字符串(虽然题目说明无首尾空格,但需考虑边界场景),代码初始linesCount = 1会错误返回1,正确结果应为0。

其他冗余操作

代码中的StringBuilder和System.out.println属于本地调试代码,在Codility平台中属于冗余操作,虽不影响结果,但建议移除避免潜在问题。

修正后的代码

public static int solution(String S, int K) {
    // 处理空输入场景
    if (S.isEmpty()) {
        return 0;
    }
    
    String[] words = S.split(" ");
    
    // 检查单个单词是否超过K长度
    for (String word : words) {
        if (word.length() > K) {
            return -1;
        }
    }
    
    int linesCount = 1;
    int currentLineLength = 0;
    
    for (String word : words) {
        // 计算当前单词加入后的总长度:如果是当前行第一个单词,不需要加空格
        int requiredLength = currentLineLength == 0 ? word.length() : currentLineLength + 1 + word.length();
        
        if (requiredLength > K) {
            // 无法加入当前行,开启新行
            linesCount++;
            currentLineLength = word.length();
        } else {
            // 加入当前行,更新行长度
            currentLineLength = requiredLength;
        }
    }
    
    return linesCount;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:03:20