Open songyy5517 opened 6 months ago
Approach: The traverse and concatenation of String
Complexity Analysis
class Solution {
public String mergeAlternately(String word1, String word2) {
// 1. Exceptions
if (word1 == null || word2 == null)
return word1 == null ? word2 : word1;
// 2. Define StringBuffer
StringBuffer sb = new StringBuffer();
int p1 = 0, p2 = 0;
while (p1 < word1.length() || p2 < word2.length()){
if (p1 < word1.length()){
sb.append(word1.charAt(p1));
p1 ++;
}
if (p2 < word2.length()){
sb.append(word2.charAt(p2));
p2 ++;
}
}
return sb.toString();
}
}
2024/5/6
You are given two strings
word1
andword2
. Merge the strings by adding letters in alternating order, starting withword1
. 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:
Example 2:
Example 3:
Intuition This problem mainly examines the operations of String. A straightforward idea is that set up two pointers to travarse two strings alternatively and then use a StringBuffer to receive the character in these strings. Another point is that when one string goes out of range, we should not iterate over it anymore, but just the other one.