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:
- Get the lengths of both strings,
mandn, and use aStringBuilderto build the result. - Use two pointers,
iforword1andjforword2, both starting at0. - Loop until both strings are exhausted: if
i < m, appendword1[i]and incrementi; ifj < n, appendword2[j]and incrementj. This takes one character from each string alternately until both are exhausted. - Convert the
StringBuilderto 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(); }}