题目
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
我的代码
class Solution {
public:
string mergeAlternately(string word1, string word2)
{
char* ptr1 = &word1[0];
char* ptr2 = &word2[0];
string word3 = word1.length()<word2.length()?word1 + word2:word2 + word1;
int i = -1;
while(*ptr1 != '\0' && *ptr2 != '\0' && i<(int)word3.length())
{
word3[++i]=*ptr1++;
word3[++i]=*ptr2++;
}
return word3;
}
};
优化写法
- 不用写指针,直接以下标表示;
- 没一开始就用str相加
class Solution {
public:
string mergeAlternately(string word1, string word2) {
int m = word1.size(), n = word2.size();
int i = 0, j = 0;
string res;
while (i < m || j < n) {
if (i < m) {
res += word1[i];
i++;
}
if (j < n) {
res += word2[j];
j++;
}
}
return res;
}
};
踩坑
- str.length()不是int类型,无法与负数直接进行比较,必须强制转换成int类型才可以
不能写成while(*ptr1 != '\0' && *ptr2 != '\0' && i<word3.length())
- char*指针指向string类型的字符串时,一直后移到空,此时指针并不为nullptr。
不能写成while(ptr1 != nullptr && ptr2 != nullptr && i<(int)word3.length())