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.


문자열 word1, word2 를 반복문을 통해 charAt(i)으로 한 글자씩 뽑아서 출력한다.
만약, 문자가 모두 끝난 경우 나머지 word의 문자를 출력한다.
class Solution {
public String mergeAlternately(String word1, String word2) {
String result = "";
int word1Length = word1.length();
int word2Length = word2.length();
int max = Math.max(word1Length, word2Length);
if (word1Length > word2Length) {
for (int i = word2Length; i < word1Length; i++) {
word2 += " ";
}
} else if (word1Length < word2Length) {
for (int i = word1Length; i < word2Length; i++) {
word1 += " ";
}
}
for (int i = 0; i < max; i++) {
result += word1.charAt(i);
result += word2.charAt(i);
}
result = result.replaceAll(" ", "");
return result;
}
}
1. String → StringBuffer
String 객체의 값은 변경할 수 없다. 한번 할당된 공간이 변하지 않는 불변자료형으로 초기화된 값에서 변경이 발생할 경우 연산에서 많은 시간과 자원을 사용한다.
StringBuffer / StringBuilder 는 가변적으로 객체의 공간이 부족해지는 경우 버퍼의 크기를 유연하게 늘려주어 값의 변경이 잦은 경우 자원을 효율적으로 사용할 수 있다.
문자열의 변경이 잦을 경우,
String보다StringBuffer를 사용하자
2. 불필요한 for문 중복
기존 코드의 경우, word의 길이가 초과되어 StringIndexOutOfBoundsException(문자열의 인덱스 초과) 예외를 방지하기 위해 길이가 긴 단어에 맞춰 짧은 단어에 " " (공백문자)를 추가하는 방법으로 풀이하였으나 조건문을 통해 단어의 길이보다 현재 인덱스가 클 경우 조건문을 추가하여 조회를 회피할 수 있다.
class Solution {
public String mergeAlternately(String word1, String word2) {
// 1. String -> StringBuffer
StringBuffer result = new StringBuffer();
int word1Length = word1.length();
int word2Length = word2.length();
int max = Math.max(word1Length, word2Length);
// 2. word 의 길이와 현재 index 비교
for (int i = 0; i < max; i++) {
if (i < word1Length) {
result.append(word1.charAt(i));
}
if (i < word2Length) {
result.append(word2.charAt(i));
}
}
return result.toString();
}
}