題目描述
給你兩個字符串 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;
}