http://code.minggr.net/leetcode-1768/
https://leetcode.com/problems/merge-strings-alternately/
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.
Return the merged string.
Example 1:
Input: word1 = “abc”, word2 = “pqr”
Output: “apbqcr”
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
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
Example 3:
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
Constraints:
1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters.
string mergeAlternately(string word1, string word2) {
int i = 0, j = 0;
string ans;
while (i < word1.size() && j < word2.size()) {
if ((i+j) % 2 == 0)
ans.push_back(word1[i++]);
else
ans.push_back(word2[j++]);
}
if (i < word1.size())
ans += word1.substr(i);
if (j < word2.size())
ans += word2.substr(j);
return ans;
}
Alternatively append the character from w1
and w2
to res
.
Complexity
Time O(n + m)
Space O(n + m)
X. Two Pointers
public String mergeAlternately(String w1, String w2) {
int n = w1.length(), m = w2.length(), i = 0, j = 0;
StringBuilder res = new StringBuilder();
while (i < n || j < m) {
if (i < w1.length())
res.append(w1.charAt(i++));
if (j < w2.length())
res.append(w2.charAt(j++));
}
return res.toString();
}
One Pointer
public String mergeAlternately(String w1, String w2) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < w1.length() || i < w2.length(); ++i) {
if (i < w1.length())
res.append(w1.charAt(i));
if (i < w2.length())
res.append(w2.charAt(i));
}
return res.toString();
}
https://walkccc.me/LeetCode/problems/1768/
string mergeAlternately(string word1, string word2) { const int n = min(word1.length(), word2.length()); string prefix; for (int i = 0; i < n; ++i) { prefix += word1[i]; prefix += word2[i]; } return prefix + word1.substr(n) + word2.substr(n); }