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

题目

给你两个字符串 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()
    }

总结

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

不管难易,贵在坚持

加油

相关推荐
music&movie1 小时前
算法工程师认知水平要求总结
人工智能·算法
laocui12 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910132 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥3 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥3 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu3 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung3 小时前
机器学习算法分类
算法·机器学习·分类
Ai多利3 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
Q8137574604 小时前
中阳视角下的资产配置趋势分析与算法支持
算法
yvestine4 小时前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示