1. 题目描述
交替合并字符串
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回合并后的字符串。
- 1 <= word1.length, word2.length <= 100
- word1 和 word2 由小写英文字母组成。
Merge Strings Alternately
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
- 1 <= word1.length, word2.length <= 100
- word1 and word2 consist of lowercase English letters.
2. 题解
2.1 C实现
2.1.1 解法一
底层逻辑:
以传入的较长字符串长度为循环次数,按照前后顺序,依次获取2个字符串中的单个字符,并添加到最终返回的字符串中。当较短的字符串全部添加完毕后,只需添加较长字符串的剩余部分即可。
代码:
char* mergeAlternately(char* word1, char* word2) {
size_t word1_len = strlen(word1);
size_t word2_len = strlen(word2);
size_t word1_used, word2_used = 0;
char* out = (char*)malloc((word1_len + word2_len) * sizeof(char) + 1);
if (out == NULL) {
return NULL;
}
size_t out_size = 0;
while (word1_used < word1_len || word2_used < word2_len) {
if (word1_used < word1_len) {
out[out_size++] = word1[word1_used++];
}
if (word2_used < word2_len) {
out[out_size++] = word2[word2_used++];
}
}
out[out_size++] = '\0';
return out;
}
代码逻辑梳理:
- 分别获得传入的2个字符串的长度。
- 分配返回值所需要的内存空间(字符串以’\0’结尾,因此要多申请1个字符的内存空间)。
- 循环遍历每个字符串,当2个字符串均遍历完成后退出循环。
- 添加’\0’结尾。
- 返回合并后的字符串。
复杂度分析:
时间复杂度:O(m+n),其中m和n分别是字符串 word1和 word2的长度。
空间复杂度:O(m+n),其中m和n分别是字符串 word1和 word2的长度。
2.2 Rust实现
第二轮刷题后完善。