1768. Merge Strings Alternately(Easy)

題目說明

Chung-chun Lo
Skyler Record
Nov 7, 2023

--

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.

簡單來說就是會給兩個字串以word1為主將兩個字串的字元分別交互合併成一個字串,如有其中一個字串長於另一個將直接合併在字串的最後面。

解題概念

這題其實就蠻簡單的分別依序做交互合併即可。

func mergeAlternately(word1 string, word2 string) string {
result:=make([]byte,0)
index:=0
for index<len(word1) || index< len(word2){
if index<len(word1){
result=append(result,word1[index])
}
if index<len(word2){
result=append(result,word2[index])
}
index++
}

return string(result)
}

--

--