Skip to content

LeetCode: 1768-Merge Strings Alternately 解題紀錄

Last Updated on 2023-04-18 by Clay

題目

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.

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.

題目會給我們兩個字串,而我們要做的就是將其交錯地排列成新的字串。比方說 abc 和 xyz,我們就要將其補成 a x b y c z,交錯地排列。

如果有一個字串長度較短,那麼新字串就直接補上還有剩餘的字串的尾部即可。


解題思路

這題由於是 Easy,也沒有太多巧妙地解法。我認為就將其交錯地組成新字串,接著判斷哪個字串較長,將其直接補上。

C++ 範例程式碼

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        // Init
        int size1 = word1.size();
        int size2 = word2.size();
        std::string mergeWord;

        // Reserve space for the merged word
        mergeWord.reserve(size1 + size2);

        // Merge
        int i = 0, j = 0;
        while (i < size1 && j < size2) {
            mergeWord.push_back(word1[i++]);
            mergeWord.push_back(word2[j++]);
        }

        // Append the remaining characters
        if (i < size1) {
            mergeWord.append(word1.substr(i));
        } 
        else {
            mergeWord.append(word2.substr(j));
        }

        return mergeWord;
    }
};



Python 範例程式碼

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        # Init
        size1 = len(word1)
        size2 = len(word2)
        mergeWord = ""

        # Merge
        i, j = 0, 0
        while i < size1 and j < size2:
            mergeWord += word1[i]
            mergeWord += word2[j]
            i += 1
            j += 1

        # Append the remaining characters
        if i < size1:
            mergeWord += word1[i:]
        else:
            mergeWord += word2[j:]

        return mergeWord

References


Read More

Leave a Reply