본문 바로가기
코딩 문제

LeetCode 1768 Merge String Alternately

by Zach Choi 2023. 7. 17.
728x90
반응형

간단한 아이디어로 풀 수 있는 쉬운 문제이다. String Class 메서드 사용에 익숙해야 한다. 훨씬 간단하게도 짤수 있는데!

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
                unsigned int minLength = 0;
        unsigned int Lengthword1 = word1.length();
        unsigned int Lengthword2 = word2.length();
        string MergedString;
        string SortedMergedString;

        if (Lengthword1 > Lengthword2)
        {
            for (unsigned int i = 0; i < (Lengthword1 - Lengthword2); ++i)
            {
                MergedString.push_back(word1[word1.length() - 1]);

                word1.pop_back();
            }

            minLength = Lengthword2;
        }
        else if (Lengthword1 < Lengthword2)
        {
            for (unsigned int i = 0; i < (Lengthword2 - Lengthword1); ++i)
            {
                MergedString.push_back(word2[word2.length() - 1]);

                word2.pop_back();
            }

            minLength = Lengthword1;
        }
        else
        {
            minLength = Lengthword1;
        }

        for (unsigned int i = 0; i < minLength; ++i)
        {
            MergedString.push_back(word2[word2.length() - 1]);
            MergedString.push_back(word1[word1.length() - 1]);

            word2.pop_back();
            word1.pop_back();
        }

        for (unsigned int i = 0; i < MergedString.length(); ++i)
        {
            SortedMergedString.push_back(MergedString[MergedString.length() - 1 - i]);
        }

        for (unsigned int i = 0; i < SortedMergedString.length(); ++i)
        {
            printf("%c ", SortedMergedString[i]);
        }
        printf("\n ");

        return SortedMergedString;
    }
};

 

아래가 훨씬 좋은 코드임.

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        string retString;
        int i = 0;
        while (i < word1.length() || i < word2.length()) {
            if (i < word1.length()) {
                retString += word1[i];
            }
            if (i < word2.length()) {
                retString += word2[i];
            }
            i++;
        }
        return retString;
    }
};
728x90
반응형

'코딩 문제' 카테고리의 다른 글

LeetCode 62. Unique Path  (0) 2023.07.27
[LeetCode] 771, Jewels and Stones  (0) 2023.02.14
[LeetCode] 1720 Decode XORred Array  (0) 2023.01.29
[LeetCode] 728. Self Dividing Numbers, C++  (0) 2023.01.26
[LeetCode] 2032. Two Out of Three, C++  (0) 2023.01.25