Featured image of post Merge Strings Alternately

Merge Strings Alternately

1768. 交替合并字符串

时间复杂度

时间复杂度 O(max(n, m))

空间复杂度

空间复杂度为 O(n + m)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution
{
public:
    string mergeAlternately(string word1, string word2)
    {
      std::string res;
      int n = word1.size(), m = word2.size();
      int i = 0, j = 0;
      while (i < n || j < m)
      {
        if (i < n) res += word1[i ++ ];
        if (j < m) res += word2[j ++ ];
      }
      return res;
    }
};
Built with Hugo
Theme Stack designed by Jimmy