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.
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
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
To merge two strings alternately, use two pointers to pick characters from each string in turn. If one string is longer, append its remaining characters at the end.
classSolution {
public: string mergeAlternately(string word1, string word2) {
int i =0, j =0, n = word1.size(), m = word2.size();
string ans;
while (i < n || j < m) {
if (i < n) ans += word1[i++];
if (j < m) ans += word2[j++];
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funcmergeAlternately(word1, word2string) string {
i, j:=0, 0n, m:= len(word1), len(word2)
ans:= make([]byte, 0, n+m)
fori < n||j < m {
ifi < n {
ans = append(ans, word1[i])
i++ }
ifj < m {
ans = append(ans, word2[j])
j++ }
}
return string(ans)
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
public String mergeAlternately(String word1, String word2) {
int i = 0, j = 0, n = word1.length(), m = word2.length();
StringBuilder ans =new StringBuilder();
while (i < n || j < m) {
if (i < n) ans.append(word1.charAt(i++));
if (j < m) ans.append(word2.charAt(j++));
}
return ans.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmergeAlternately(word1: String, word2: String): String {
var i = 0; var j = 0val n = word1.length; val m = word2.length
val ans = StringBuilder()
while (i < n || j < m) {
if (i < n) ans.append(word1[i++])
if (j < m) ans.append(word2[j++])
}
return ans.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
defmerge_alternately(word1: str, word2: str) -> str:
i, j =0, 0 n, m = len(word1), len(word2)
ans = []
while i < n or j < m:
if i < n:
ans.append(word1[i])
i +=1if j < m:
ans.append(word2[j])
j +=1return''.join(ans)
impl Solution {
pubfnmerge_alternately(word1: String, word2: String) -> String {
let (mut i, mut j) = (0, 0);
let (n, m) = (word1.len(), word2.len());
letmut ans = String::with_capacity(n + m);
let w1 = word1.as_bytes();
let w2 = word2.as_bytes();
while i < n || j < m {
if i < n {
ans.push(w1[i] aschar);
i +=1;
}
if j < m {
ans.push(w2[j] aschar);
j +=1;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
mergeAlternately(word1: string, word2: string):string {
leti=0, j=0, n=word1.length, m=word2.length;
letans='';
while (i<n||j<m) {
if (i<n) ans+=word1[i++];
if (j<m) ans+=word2[j++];
}
returnans;
}
}