點我看題目
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;
}
};
目前分類:leetcode (1)
- Nov 26 Sun 2023 15:06
leetcode 1768. Merge Strings Alternately