Skip to content
thesarfo

Reference

Merge Strings Alternately

Merging two strings by alternating characters from each, appending the remainder of the longer string at the end.

views 0

Merge two strings together by alternating characters from each — take one character from each string in turn, and if one string is longer, append its remaining characters at the end. (LeetCode 1768)

Approach:

  1. Get the lengths of both strings, m and n, and use a StringBuilder to build the result.
  2. Use two pointers, i for word1 and j for word2, both starting at 0.
  3. Loop until both strings are exhausted: if i < m, append word1[i] and increment i; if j < n, append word2[j] and increment j. This takes one character from each string alternately until both are exhausted.
  4. Convert the StringBuilder to a string and return it.

For word1 = "abc", word2 = "defg", the merge produces "adbcef", then the remaining "g" from word2 gets appended for "adbcefg".

class Solution {
public String mergeAlternately(String word1, String word2) {
int m = word1.length();
int n = word2.length();
StringBuilder result = new StringBuilder();
int i = 0;
int j = 0;
while(i < m || j < n){
if (i < m){
result.append(word1.charAt(i));
i++;
}
if (j < n){
result.append(word2.charAt(j));
j++;
}
}
return result.toString();
}
}