交替合并字符串

题目

给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。

我的解答

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        int len = len1 > len2 ? len1 : len2;
        String result = "";
        if (len1 <= 1) {
            result = word1 + word2;
            return result;
        }
        for (int i = 0; i < len; i++) {
            if (i < len1) {
                result += word1.charAt(i);
            }
            if (i < len2) {
                result += word2.charAt(i);
            }
        }
        return result;
    }
}

DeepSeek的解答

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int l1 = word1.length();
        int l2 = word2.length();
        int maxLen = Math.max(l1, l2);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < maxLen; i++) {
            if (i < l1) {
                result.append(word1.charAt(i));
            }
            if (i < l2) {
                result.append(word2.charAt(i));
            }
        }
        return result.toString();
    }
}

通义灵码

通义灵码的代码写的不行,过于啰嗦了,此处不赘述了。

总结

DeepSeek的方案:内存占用减少 90% 以上(实测 10 万次拼接场景下,StringBuilder 比 + 节省 99.9% 内存)。
以后还是尽量使用StringBuilder代替+。

posted @ 2025-05-09 10:08  尼兰  阅读(5)  评论(0)    收藏  举报