解释:字符串合并情况如下所示: word1: ab c word2: pq r 合并后: apbq c r
示例 2:
1 2 3 4 5 6 7 8
输入:word1 = "ab", word2 = "pqrs"
输出:"apbqrs"
解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。 word1: ab word2: pq r s 合并后: apbq r s
示例 3:
1 2 3 4 5 6 7 8
输入:word1 = "abcd", word2 = "pq"
输出:"apbqcd"
解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。 word1: ab c d word2: pq 合并后: apbq c d
提示:
$1 <= word1.length, word2.length <= 100$
word1 和 word2 由小写英文字母组成
模拟
根据题意进行模拟即可。
Java 代码:
1 2 3 4 5 6 7 8 9 10 11
classSolution { public String mergeAlternately(String s1, String s2) { intn= s1.length(), m = s2.length(), i = 0, j = 0; StringBuildersb=newStringBuilder(); while (i < n || j < m) { if (i < n) sb.append(s1.charAt(i++)); if (j < m) sb.append(s2.charAt(j++)); } return sb.toString(); } }
TypeScript 代码:
1 2 3 4 5 6 7 8 9
functionmergeAlternately(s1: string, s2: string): string { let n = s1.length, m = s2.length, i = 0, j = 0 let ans = "" while (i < n || j < m) { if (i < n) ans += s1[i++] if (j < m) ans += s2[j++] } return ans }
Python 代码:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmergeAlternately(self, s1: str, s2: str) -> str: n, m, i, j = len(s1), len(s2), 0, 0 ans = "" while i < n or j < m: if i < n: ans += s1[i] i += 1 if j < m: ans += s2[j] j += 1 return ans