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

LeetCode 1768:我的交替合并字符串函数存在问题,请求排查

问题排查与修复

你的代码核心问题在于两个独立的if语句会导致单次循环中可能添加两个字符,甚至触发数组越界访问,最终输出结果不符合预期。

具体问题分析

以测试用例word1 = "abc", word2 = "pqr"为例,循环执行到i=4时:

  1. 第一个if条件满足(i为偶数,j=2 < 3),向结果中添加c,j变为3;
  2. 第二个if的条件j == len1为true,因此会继续执行,向结果中添加r,k变为3;
    此时结果字符串长度已经超出预期,后续i=5时,第一个if的k == len2为true,会尝试访问word1[3]——这已经超出了word1的索引范围(合法索引为0-2),属于越界访问。

另外,当其中一个字符串遍历完成后,你的逻辑没有停止交替判断,而是继续根据i的奇偶性尝试添加字符,导致逻辑混乱。

修复方案

我们可以调整逻辑,先交替添加两个字符串的字符,直到其中一个遍历完成,再将剩余字符串的全部字符追加到结果中。这种方式逻辑清晰,避免了越界问题:

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int len1 = word1.size();
        int len2 = word2.size();
        string ans;
        // 预分配内存,提升拼接效率
        ans.reserve(len1 + len2);
        
        int idx = 0;
        // 交替添加两个字符串的字符
        while (idx < len1 && idx < len2) {
            ans += word1[idx];
            ans += word2[idx];
            idx++;
        }
        
        // 添加剩余的字符
        if (idx < len1) {
            ans += word1.substr(idx);
        }
        if (idx < len2) {
            ans += word2.substr(idx);
        }
        
        return ans;
    }
};

如果你想保留原有的循环结构,也可以将两个if改为if-else结构,确保单次循环只添加一个字符:

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        string ans;
        int j = 0, k = 0;
        
        for (int i = 0; j < len1 || k < len2; i++) {
            // 优先交替添加,若其中一个字符串已用完则直接添加剩余部分
            if (j < len1 && (i % 2 == 0 || k >= len2)) {
                ans += word1[j++];
            } else if (k < len2) {
                ans += word2[k++];
            }
        }
        
        return ans;
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:12:44