ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • LeetCode - 1768. Merge Strings Alternately (Java)
    개발/코딩테스트 2023. 8. 23. 11:20

    문제: 1768. Merge Strings Alternately (Easy)

     

    문자열 word1, word2 가 주어지고 한 문자씩 교대로 합친 문자열을 만들고 길이가 달라 남는 문자열은 끝에 추가한 최종 문자열을 반환하는 문제.

     

    예시:

     

    Example 1:
    Input: word1 = "abc", word2 = "pqr"

    Output: "apbqcr"

    Explanation: word1 과 word2 가 한 문자씩 합쳐진다.
    Example 2:
    Input: word1 = "ab", word2 = "pqrs"

    Output: "apbqrs"

    Explanation: word1 과 word2 가 한 문자씩 합쳐져 "apbq" 가 되고, word2 의 남는 문자열인 "rs" 를 합쳐 "apbqrs" 가 된다.
    Example 3:
    Input: word1 = "abcd", word2 = "pq"

    Output: "apbqcd"

    Explanation: word1 과 word2 가 한 문자씩 합쳐져 "apbq" 가 되고, word1의 남는 문자열인 "cd" 를 합쳐 "apbqcd" 가 된다.

     

    풀이:

     

    class Solution {
        public String mergeAlternately(String word1, String word2) {
            StringBuilder result = new StringBuilder();
    
            int cursor = 0;
            while (cursor != word1.length() && cursor != word2.length()) {
                result.append(word1.charAt(cursor));
                result.append(word2.charAt(cursor));
                cursor++;
            }
    
            if (cursor < word1.length()) {
                while (cursor != word1.length()) {
                    result.append(word1.charAt(cursor));
                    cursor++;
                }
            }
            if (cursor < word2.length()) {
                while (cursor != word2.length()) {
                    result.append(word2.charAt(cursor));
                    cursor++;
                }
            }
    
            return result.toString();
        }
    }

     

    설명:

     

    1. result 로 반환하기 위한 문자열을 만들 StringBuilder 를 선언.

    2. cursor를 0으로 선언하고 word1 또는 word2 의 길이가 끝날 때 까지 cursor를 늘려가며 순차적으로 한 문자씩 result에 append.

    3. while문 종료 후 cursor 보다 더 긴 word1 또는 word2 가 있을 경우 나머지 문자를 result에 append.

    4. result 리턴.

     

    시간복잡도: O(n)

    공간복잡도: O(1)

     

    Runtime: 1ms Beats 78.87% of users with Java

    Memory: 40.80MB Beats 59.24% of users with Java


     

    개인의 해답으로 풀이한 문제입니다. 
    절대적인 정답이 아닐 수 있으며, 더 좋은 개선 방안이 있다면 댓글로 의견 주세요.
Designed by Tistory.