给你两个字符串 word1
和 word2
。请你从 word1
开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串
示例 1:
输入:word1 = "abc", word2 = "pqr" 输出:"apbqcr" 解释:字符串合并情况如下所示: word1: a b c word2: p q r 合并后: a p b q c r
示例 2:
输入:word1 = "ab", word2 = "pqrs" 输出:"apbqrs" 解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。 word1: a b word2: p q r s 合并后: a p b q r s
示例 3:
输入:word1 = "abcd", word2 = "pq" 输出:"apbqcd" 解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。 word1: a b c d word2: p q 合并后: a p b q c d
提示:
1 <= word1.length, word2.length <= 100
word1
和word2
由小写英文字母组成
一.涉及知识点:
字符串基本操作
1.字符串的拼接
可使用'+'、'+='进行连接,亦可用append函数进行连接。
string s1,s2,s3;
s1="mail ";
s2="time sh ";
s3=s1+s2; //使用'+'拼接
s1.append("hello "); //在s1末尾连接
2.字符串的插入、删除及替换函数
insert():s1.insert(pos,str) 在s1的第pos个位置插入str字符串
erase(): s1.erase(pos,n) 删除s1第pos位置后的连续n个字符
replace():s1.replace(pos,n,str) 将s1的pos位置开始的连续n个字符替换为str
3.字符串的切片
substr函数用于截取字符串,即求子串。基本格式:变量名.substr(int pos , int n),函数返回从pos位置开始的连续n个字符组成的字符串。
4.string的构造函数的形式
string str1; //生成空字符串
str1 = "Hello World!";
string str2(str1); //生成str1的复制品
string str3("12345", 0, 3); //结果为"123"
string str4("012345", 5); //结果为"01234"
string str5(5, '1'); //结果为"11111"
string str6(str2, 6); //结果为"World!"
char alls[] = "All's well that ends well";
string str7(alls,10);//结果为 All's well
二.代码
思路:
得到两者字符串长度,先交替把长度短的连完。之后根据已知短字符串的长度,在其后连接较长字符串剩下的字符。
class Solution {
public:
string mergeAlternately(string word1, string word2) {
string ans;
int a1,a2,a;
a1=word1.length();
a2=word2.length();
a=min(a1,a2);
for(int i=0;i<=a-1;i++)
{
ans+=word1[i];
ans+=word2[i];
}
if(a1>a2)
{
for(int i=a;i<a1;i++)
{
ans=ans+word1[i];
}
}
else
{
for(int i=a;i<a2;i++)
{
ans=ans+word2[i];
}
}
return ans;
}
};