Leetcode - 1768. Merge Strings Alternately

숲사람·2023년 8월 16일
0

멘타트 훈련

목록 보기
226/237

문제

두 문자열을 한문자씩 번갈아서 합쳐라. 더 긴 문자열의 나머지 문자열은 그대로 합치기.

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

아디이어

다음과 같은 재귀적 구조로 작성. 풀이가 비슷했던 문제로는 Leetcode - 21. Merge Two Sorted Lists

recursive(w1, w2):
	w1[0] + w2[0] + recursive(w1[1..], w2[1..])

풀이

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        if (word1.size() == 0) return word2;
        if (word2.size() == 0) return word1;

        string ret = "";
        ret = ret + word1[0] + word2[0];
        return ret + mergeAlternately(word1.substr(1), word2.substr(1));
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글