【LeetCode】1768_交替合并字符串_C
题目描述
给你两个字符串 word1
和 word2
。请你从 word1
开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
https://leetcode.cn/problems/merge-strings-alternately/description/
示例
示例 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是我自己的写法,写完之后感觉有点冗余,但又不知如何改进,实现方式2则是借鉴了别人的题解,显然,方式2的代码更加简洁优雅
代码实现
- 实现方式1
char * mergeAlternately(char * word1, char * word2){ int length1 = strlen(word1); int length2 = strlen(word2); char* res = (char*)malloc(sizeof(char) * (length1 + length2 + 1)); int i = 0; int j = 0; while(word1[i] != 0 && word2[i] != 0) { res[j] = word1[i]; j++; res[j] = word2[i]; i++; j++; } if(word1[i] == 0) { while(word2[i] != 0) { res[j] = word2[i]; i++; j++; } } else { while(word1[i] != 0) { res[j] = word1[i]; i++; j++; } } res[j] = 0; return res; }
- 实现方式2
char * mergeAlternately(char * word1, char * word2) { int length1 = strlen(word1); int length2 = strlen(word2); char* res = malloc(sizeof(char) * (length1 + length2 + 1)); int i = 0; int j = 0; while (i < length1 || i < length2) { if (i < strlen(word1)) { res[j++] = word1[i]; } if (i < strlen(word2)) { res[j++] = word2[i]; } i++; } res[j] = 0; return res; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具