【题解】1768. 交替合并字符串 (双指针、字符串)

https://leetcode.cn/problems/merge-strings-alternately/description/?envType=study-plan-v2&envId=leetcode-75
在这里插入图片描述

class Solution {
    
    
public:
    string mergeAlternately(string word1, string word2) {
    
    
        int m = word1.size(), n = word2.size();
        int i = 0, j = 0;
        string ans;
        ans.reserve(m + n); // 不要写成reverse,reserve提前分配好内存,以免频繁扩容
                            // resize是实际调整容器大小
        while (i < m || j < n)
        {
    
    
            if (i < m) {
    
    
                ans.push_back(word1[i++]);
            }  
            if (j < n) {
    
    
                ans.push_back(word2[j++]);
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/Colorful___/article/details/141277366