Keshawn_lu's Blog

Leetcode 1768. 交替合并字符串

字数统计: 234阅读时长: 1 min
2022/10/23 Share

题目简介:

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

返回 合并后的字符串

示例 1:

1
2
3
4
5
6
输入:word1 = "abc", word2 = "pqr"
输出:"apbqcr"
解释:字符串合并情况如下所示:
word1: a b c
word2: p q r
合并后: a p b q c r

提示:

  • 1 <= word1.length, word2.length <= 100
  • word1word2 由小写英文字母组成

思路:

依次遍历即可,注意需要将多余字符放至末尾。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
string mergeAlternately(string word1, string word2) {

int size = min(word1.size(), word2.size());
string res;
int i;
for(i = 0; i < size; i++){

res += word1[i];
res += word2[i];
}

while(i < word1.size()){

res += word1[i++];
}

while(i < word2.size()){

res += word2[i++];
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: