Solved
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.
Example 1:
Input: word1 = "abc", word2 = "pqr" Output: "apbqcr" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs" Output: "apbqrs" Explanation: Notice that as word2 is longer, "rs" is appended to the end. word1: a b word2: p q r s merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq" Output: "apbqcd" Explanation: Notice that as word1 is longer, "cd" is appended to the end. word1: a b c d word2: p q merged: a p b q c d
Constraints:
1 <= word1.length, word2.length <= 100
word1
andword2
consist of lowercase English letters.
google 翻譯:
給定兩個字串 word1 和 word2。透過以交替順序添加字母來合併字串,從 word1 開始。
如果一個字串比另一個字串長,請將附加字母附加到合併字串的末尾。
想法一:
使用一個 i 變數取 2 的餘數,
等於 0 時抓 word2 (如果 word2 已抓完了,就改抓 word1),
等於 1 時抓 word1 (如果 word1 已抓完了,就改抓 word2)。
寫法一:
結果一:
char * mergeAlternately(char * word1, char * word2){
int len1= (word1 ?: strlen(word1));
int len2 = (word2 ?: strlen(word2));
int len = len1 + len2;
char *str = malloc(len + 4);
char *p1 = word1, *p2 = word2;
int i = 0;
while(*p1 || *p2) {
if(i % 2) {
if(*p2) {
*(str+i) = *p2;
p2++;
} else {
*(str+i) = *p1;
p1++;
}
} else {
if(*p1) {
*(str+i) = *p1;
p1++;
} else {
*(str+i) = *p2;
p2++;
}
}
i++;
}
*(str+i) = '\0';
return str;
}
速度尚可接受,但記憶體差別人太多了,看來有更簡潔的寫法
想法二:
參考了大神的寫法,發現跟本不需要 i 變數,跑一次迴圈直接看兩個 word 即可,大神真是厲害。
寫法二:
char * mergeAlternately(char * word1, char * word2){
int len1= (word1 ? strlen(word1) : 0);
int len2 = (word2 ? strlen(word2) : 0);
char *str = malloc(len1 + len2 + 4);
int i = 0, j = 0;
while(i<len1 || i<len2) {
if(i<len1) {
*(str+j) = *(word1+i);
j++;
}
if(i<len2) {
*(str+j) = *(word2+i);
j++;
}
i++;
}
*(str+j) = '\0';
return str;
}
結果二:
結果已經很接近完美了想法三:
再看一下其他大神有什麼想法可以參考的。
最後決定不使用 i、j 變數,改用 w1、w2 指標判斷字元,看起來更簡潔些。
再加上 isalnum 的錯誤判斷,就更沒有缺點了。
寫法三:
char * mergeAlternately(char * word1, char * word2){
int len1= (word1 ? strlen(word1) : 0);
int len2 = (word2 ? strlen(word2) : 0);
char *str = malloc(len1 + len2 + 4);
char *w1 = word1, *w2 = word2, *s = str;
while(*w1 || *w2) {
if(*w1) {
if(isalnum(*w1)) {
*s++ = *w1;
}
w1++;
}
if(*w2) {
if(isalnum(*w2)) {
*s++ = *w2;
}
w2++;
}
}
*s = '\0';
return str;
}
結果三:
速度和記憶體都還令人滿意~
沒有留言:
張貼留言