c++练习一:交替合并字符串
引言
看了一段时间的c++ 拿leetcode上的题目来练练手,话不多说先看题目:
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。返回合并后的字符串 。
实现
有两种方法第一种双重循环暴力破解,第二种利用指针用两个指针 i 和 j,初始时分别指向两个字符串的首个位置。随后的每次循环中,依次进行如下的两步操作:
- 如果 i 没有超出 word1的范围,则将 word1[i] 加入返回值,并将 i 移动一个位置
- 如果 j 没有超出 word2的范围,则将 word2[j] 加入返回值,并将 j 移动一个位置
当 i 和 j 都超出对应的范围后,结束循环并返回答案即可。
实现一
#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
string mergeAlternately(string word1, string word2)
{
string target = "";
int length1 = word1.size();
int length2 = word2.size();
if(length1==length2)
{
for(int i=0;i<length1;i++)
{
target.append(1,word1[i]);
target.append(1,word2[i]);
}
}else if(length1<length2)
{
for(int i=0;i<length1;i++)
{
target.append(1,word1[i]);
target.append(1,word2[i]);
}
target.append(word2,length1,length2);
}
else
{
for(int i=0;i<length2;i++)
{
target.append(1,word1[i]);
target.append(1,word2[i]);
}
target.append(word1,length2,length1);
}
return target;
}
};
int main()
{
Solution s;
string word1 = "abcd";
string word2 = "EF";
string res = s.mergeAlternately(word1, word2);
cout << res << endl;
}
实现二
#include<iostream>
#include <string>
using namespace std;
class Solution
{
public:
string mergeAlternately(string word1, string word2)
{
int ptr1 = 0, ptr2 = 0;
string res = "";
while (ptr1 != word1.size() && ptr2 != word2.size())
{
res += word1[ptr1++];
res += word2[ptr2++];
}
if (ptr1 == word1.size() && ptr2 != word2.size())
{
while (ptr2 != word2.size())
{
res += word2[ptr2++];
}
}
else if (ptr2 == word2.size() && ptr1 != word1.size())
{
while (ptr1 != word1.size())
{
res += word1[ptr1++];
}
}
return res;
}
};
int main()
{
Solution s;
string word1 = "abcd";
string word2 = "EF";
string res = s.mergeAlternately(word1, word2);
cout << res << endl;
}