Judie 发表于 2023-6-1 09:17:36

【朱迪的LeetCode刷题笔记】1768. Merge Strings Alternately #Easy #Python #C++

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.

Judy
Python
class Solution(object):
    def mergeAlternately(self, word1, word2):
      """
      :type word1: str
      :type word2: str
      :rtype: str
      """
      l1 = len(word1)
      l2 = len(word2)
      i1 = 0
      i2 = 0
      r = ""
      while i1 < l1 and i2 < l2:
            r += word1 + word2
            i1 += 1
            i2 += 1
      r += word1 + word2
      return r

Gray
C++
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
      int acc = 0;
      string ans;
      for(int i = 0; i < word1.size(); i++){
            ans += word1;
            if(acc == word2.size()){//走完
                continue;
            }else {//没走完
                ans+= word2;
            }
            acc++;
      }
      if(acc < word2.size()){
            ans += word2.substr(acc,word2.size()-acc);
      }
      return ans;
    }
};

Mike
C++
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
      int index = 0;
      string s = "";
      int len1 = word1.length();
      int len2 = word2.length();
      int baselen = min(len1, len2);
      for (int index = 0; index < baselen; index++) {
            s += word1;
            s += word2;
      }
      if (word2.length() > word1.length()) {
            s += word2.substr(baselen, word2.length() - baselen);
      } else {
            s += word1.substr(baselen, word1.length() - baselen);
      }
      return s;
    }
};
页: [1]
查看完整版本: 【朱迪的LeetCode刷题笔记】1768. Merge Strings Alternately #Easy #Python #C++