1768.Merge Strings Alternately
===
###### tags: `Easy`,`String`,`Two Pointers`
[1768. Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/)
### 題目描述
You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return *the merged string*.
### 範例
**Example 1:**
```
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
```
**Example 2:**
```
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
```
**Example 3:**
```
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
```
**Constraints**:
* 1 <= `word1.length`, `word2.length` <= 100
* `word1` and `word2` consist of lowercase English letters.
### 解答
#### Javascript
```javascript=
function mergeAlternately(word1, word2) {
const result = [];
for (let i = 0; i < 100; i++) {
if (!word1[i] && !word2[i]) break;
result.push(word1[i] ?? '');
result.push(word2[i] ?? '');
}
return result.join('');
}
```
> [name=Marsgoat][time=Apr 18, 2023]
#### Python
```python=
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
ans = []
for ch1, ch2 in zip_longest(word1, word2, fillvalue=''):
ans.append(ch1 + ch2)
return "".join(ans)
```
上面邏輯縮成一行
```python=
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
return "".join(ch1 + ch2 for ch1, ch2 in zip_longest(word1, word2, fillvalue=''))
```
> [name=Ron Chen][time=Tue, Apr 18, 2023]
#### Java
練習 Java Stream API
```java=
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
IntStream.range(0, Math.min(word1.length(), word2.length()))
.forEach(i -> sb.append(word1.charAt(i))
.append(word2.charAt(i)));
if(word1.length() > word2.length()) {
sb.append(word1.substring(word2.length()));
} else {
sb.append(word2.substring(word1.length()));
}
return sb.toString();
}
}
```
> [name=Ron Chen][time=Tue, Apr 18, 2023]
#### TypeScript
```typescript=
function mergeAlternately(word1: string, word2: string): string {
let result = '';
if (word1.length >= word2.length) {
for (let i = 0; i < word1.length; i++) {
result += word1.charAt(i);
result += word2.charAt(i);
}
} else {
for (let i = 0; i < word2.length; i++) {
result += word1.charAt(i);
result += word2.charAt(i);
}
}
return result;
}
```
> Note: `String.prototype.charAt()` 如果超過索引值會回傳空字串
> [name=Sheep][time=Apr 18, 2023]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)