Try   HackMD

【LeetCode】 1768. Merge Strings Alternately

Description

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.

Constraints:

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

給你兩個字串 word1word2。從 word1 開始,透過交替的順序將字串們合併。如果一個字串比另一個長,將多的字母加到合併字串的尾端。
回傳合併後的字串。

限制:

  • 1 <= word1.length, word2.length <= 100
  • word1word2 只包含小寫英文字母。

Example:

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

Solution

  • 題目給予的限制很少,因此作法很多,以下是不省時間及記憶體,但最直覺的作法:
  1. 宣告一個空字串用來放合併字串
    • 想省記憶體的話,應該直接在 word1word2 現有空間操作
  2. 依序將 word1word2 的字母放進去,直到其中一個放完了
    • 直接用 for loop 實作即可,判斷式的地方用 And 合併
  3. 將多的部分接到合併字串後面
    • C++ 提供 string append 函式
    • 利用下面的寫法可以不用判斷是哪個字串比較長,因為短字串取出來的會是空字串
      • 另一個想法是一開始就先判斷哪個比較長,然後透過交換字串將長字串放到 word1
  • 如果用 C 語言,只需要在一開始宣告一個 word1.size() + word2.size() 的 char* 空間即可

Code

class Solution { public: string mergeAlternately(string word1, string word2) { string ans; int count; for(count = 0; count < word1.length() && count < word2.length(); count++) { ans.push_back(word1[count]); ans.push_back(word2[count]); } ans.append(word1.begin() + count, word1.end()); ans.append(word2.begin() + count, word2.end()); return ans; } };
tags: LeetCode C++