Try   HackMD

1768.Merge Strings Alternately

tags: Easy,String,Two Pointers

1768. 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

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(''); }

MarsgoatApr 18, 2023

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)

上面邏輯縮成一行

class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return "".join(ch1 + ch2 for ch1, ch2 in zip_longest(word1, word2, fillvalue=''))

Ron ChenTue, Apr 18, 2023

Java

練習 Java Stream API

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(); } }

Ron ChenTue, Apr 18, 2023

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() 如果超過索引值會回傳空字串
SheepApr 18, 2023

Reference

回到題目列表