Game Tech Blog

1768. Merge Strings Alternately 본문

Algorithm/LeetCode

1768. Merge Strings Alternately

jonghow 2023. 7. 6. 01:31
반응형

[문제]

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.

 

[TC]

 

Example 1:

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1:  a   b   c
word2:    p   q   r
merged: a p b q c r

Example 2:

Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1:  a   b 
word2:    p   q   r   s
merged: a p b q   r   s

Example 3:

Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1:  a   b   c   d
word2:    p   q 
merged: a p b q c   d

* Constraints:

  • 1 <= word1.length, word2.length <= 100
  • word1 and word2 consist of lowercase English letters.

[접근]

문제와 TC를 보면 각 스트링에 첫 글자씩 가져와서 넣는것 뿐이다. 

별다른 문제는 보이지않고, 더 큰 string 사이즈를 가져와서 Combine 해준후에 리턴시키는게 정답일 것으로 접근해보았다.

 

[코드] C#

-> 메모리를 조금더 최적화해본다고 StringBuilder 클래스를 사용해보았다. 

using System;

public class Solution {
    public string MergeAlternately(string word1, string word2) {

        int count = word1.Length >= word2.Length ? word1.Length : word2.Length;
        StringBuilder sb = new StringBuilder(); 

        for(int i= 0 ; i < count; ++i)
        {
            if(word1.Length > i)
            {
                sb.Append(word1[i]);
                // result += word1[i];
            }

            if(word2.Length > i)
            {
                sb.Append(word2[i]);
                // result += word2[i];
            }
        }


        return sb.ToString();
    }
};

 

[결과]

[후기]

가장 쉬운 Easy의 첫 문제라서 그런지 어려울것은 없었다. 사용할 수 있는 언어가 C# 이고 예전에 C++을 다뤄본 기억이있어서 C# 풀고 C++로 변형해서도 풀어보았다. 확실히 런타임 속도는 비교할 수 없을정도로 빠른 결과를 보여주었다.

영어 문제에도 익숙해지는것이 중요해 보인다.

 

반응형

'Algorithm > LeetCode' 카테고리의 다른 글

151. Reverse Words in a String  (0) 2023.07.11
345. Reverse Vowels of a String  (0) 2023.07.10
605. Can Place Flowers  (0) 2023.07.10
1431. Kids With the Greatest Number of Candies  (0) 2023.07.07
1071. Greatest Common Divisor of Strings  (0) 2023.07.07
Comments