|
4 | 4 | * @return {string}
|
5 | 5 | */
|
6 | 6 | var mergeAlternately = function (word1, word2) {
|
7 |
| - let str = ""; |
| 7 | + let str = "", processWord = [], appendWord = [] |
| 8 | + |
8 | 9 | word1 = word1.split(""), word2 = word2.split("");
|
9 |
| - while (word1.length > 0 || word2.length > 0) { |
10 |
| - let curr1 = "", curr2 = ""; |
11 |
| - console.log(word1) |
12 |
| - console.log(word2) |
13 |
| - if (word1.length > 0) { |
14 |
| - curr1 = word1.shift(); |
15 |
| - } |
16 |
| - |
17 |
| - if (word2.length > 0) { |
18 |
| - curr2 = word2.shift(); |
19 |
| - } |
20 |
| - |
21 |
| - str += curr1 + curr2; |
| 10 | + // use the short one to process |
| 11 | + // if (word1.length <= word2.length) { |
| 12 | + processWord = word1; |
| 13 | + appendWord = word2; |
| 14 | + // } else { |
| 15 | + // processWord = word2; |
| 16 | + // appendWord = word1; |
| 17 | + // } |
| 18 | + |
| 19 | + for (let i = 0; i < word1.length; i++) { |
| 20 | + console.log("word1") |
| 21 | + console.log(word1[i]) |
| 22 | + str += word1[i]; |
| 23 | + if (word2.length > 0) str += word2.shift(); |
22 | 24 | }
|
23 | 25 |
|
| 26 | + console.log("str") |
| 27 | + console.log(str) |
| 28 | + |
| 29 | + str += word2.join(""); |
| 30 | + |
| 31 | + // while (word1.length > 0 || word2.length > 0) { |
| 32 | + // let curr1 = "", curr2 = ""; |
| 33 | + // console.log(word1) |
| 34 | + // console.log(word2) |
| 35 | + // if (word1.length > 0) { |
| 36 | + // curr1 = word1.shift(); |
| 37 | + // } |
| 38 | + // |
| 39 | + // if (word2.length > 0) { |
| 40 | + // curr2 = word2.shift(); |
| 41 | + // } |
| 42 | + // |
| 43 | + // str += curr1 + curr2; |
| 44 | + // } |
| 45 | + |
24 | 46 | return str;
|
25 | 47 | };
|
| 48 | + |
26 | 49 | let x =
|
27 |
| - mergeAlternately("abc", "pqr") |
| 50 | + // mergeAlternately("abc", "pqr") |
| 51 | + mergeAlternately("ab", "pqrs") |
| 52 | + // mergeAlternately("abcd", "pq") |
28 | 53 |
|
29 | 54 | console.log("Res")
|
30 | 55 | console.log(x)
|
0 commit comments