문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
2개의 문자열 word1과 word2가 주어진다. word1부터 시작해서 문자를 번갈아 가면서 추가해서 문자열을 병합해라. 만약 문자열이 다른 문자열보다 길다면, 병합된 문자열 끝에 추가해라.
병합된 문자열을 반환해라.
#1
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: 병합된 문자열은 다음과 같이 병합된다.
word1: a b c
word2: p q r
merged: a p b q c r
#2
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: word2가 더 길어서, "rs"는 뒤에 나타난다.
word1: a b
word2: p q r s
merged: a p b q r s
#3
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: word1이 더 길어서, "cd"는 뒤에 나타난다.
word1: a b c d
word2: p q
merged: a p b q c d
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
int max = Math.max(word1.length(), word2.length());
for(int i = 0; i < max; i++){
if(i < word1.length()){
sb.append(word1.charAt(i));
}
if(i < word2.length()){
sb.append(word2.charAt(i));
}
}
return sb.toString();
}
}