算法---交替合并字符串

题目

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

返回 合并后的字符串 。

示例 1:

输入:word1 = "abc", word2 = "pqr"

输出:"apbqcr"

解释:字符串合并情况如下所示:

word1: a b c

word2: p q r

合并后: a p b q c r

示例 2:

输入:word1 = "ab", word2 = "pqrs"

输出:"apbqrs"

解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。

word1: a b

word2: p q r s

合并后: a p b q r s

示例 3:

输入:word1 = "abcd", word2 = "pq"

输出:"apbqcd"

解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。

word1: a b c d

word2: p q

合并后: a p b q c d

提示:

1 <= word1.length, word2.length <= 100

word1 和 word2 由小写英文字母组成

解决思路

解决方法

kotlin 复制代码
    fun mergeAlternately(word1: String, word2: String): String {
        val stringBuilder = StringBuilder()
        val largeLength = word1.length.coerceAtLeast(word2.length)
        for (i in 0 until largeLength) {
            if (i < word1.length){
                stringBuilder.append(word1[i])
            }
            if (i < word2.length){
                stringBuilder.append(word2[i])
            }
        }

        return stringBuilder.toString()
    }

总结

太简单了吧,其实可以使用数组去做

不管难易,贵在坚持

加油

相关推荐
phltxy3 小时前
C语言操作符详解
java·c语言·算法
aqiu1111113 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考4 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾5 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研6 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a187927218317 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297487 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展