點我看題目

class Solution 
{
public:
    string mergeAlternately(string word1, string word2) 
    {
        string result="";
        int length1 = word1.length(), length2 = word2.length();
        int minLength = min(length1, length2);

        // 使用 for 循环交替添加字符
        for (int i = 0; i < minLength; i++) 
        {
            result += word1[i];
            result += word2[i];
        }

        // 添加剩余的字符
        for (int i = minLength; i < length1; i++) 
        {
            result += word1[i];
        }
        for (int i = minLength; i < length2; i++) 
        {
            result += word2[i];
        }

        return result;
    }
};

戰昇 發表在 痞客邦 留言(0) 人氣()