1768. Merge Strings Alternately¶
Given two strings 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.
Intuition¶
- Iterate and keep adding characters from the string alternatively
Approach¶
- Iterate and add character alternatively till we reach the end of the string word1 or word2
- Add the remaining character as it is
Complexity¶
- Time complexity : O(m+n)
- where the m,n are the length of the string word1 & word2
- Space complexity : O(m+n)
- we store the merged string
Code¶
public String mergeAlternately(String word1, String word2) {
if(word1.length() == 1) return word1+word2;
StringBuilder mergedString = new StringBuilder();
int i = 0, j = 0;
for (; i < word1.length() && j < word2.length();) {
mergedString.append(word1.charAt(i++));
mergedString.append(word2.charAt(j++));
}
if(word1.length() > i) {
mergedString.append(word1.substring(j,word1.length()));
return mergedString.toString();
}
if(word2.length() > j) {
mergedString.append(word2.substring(j,word2.length()));
return mergedString.toString();
}
return mergedString.toString();
}