[Array / String, Easy] Merge Strings Alternately

송재호·2025년 3월 9일
0

https://leetcode.com/problems/merge-strings-alternately/description/?envType=study-plan-v2&envId=leetcode-75

인덱스 두개로 이어나가면 쉽다.
이것도 충분히 답이 되지만 StringBuilder 대신 char array를 사용해서 시간을 더 줄이는 방법도 있음

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int word1Index = 0;
        int word2Index = 0;

        StringBuilder sb = new StringBuilder();

        while (word1Index < word1.length() && word2Index < word2.length()) {
            sb.append(word1.charAt(word1Index++));
            sb.append(word2.charAt(word2Index++));
        }

        while (word1Index < word1.length()) {
            sb.append(word1.charAt(word1Index++));
        }

        while (word2Index < word2.length()) {
            sb.append(word2.charAt(word2Index++));
        }

        return sb.toString();
    }
}
profile
식지 않는 감자

0개의 댓글