|
| 1 | +/** |
| 2 | + * 1754. Largest Merge Of Two Strings |
| 3 | + * https://leetcode.com/problems/largest-merge-of-two-strings/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two strings word1 and word2. You want to construct a string merge in the |
| 7 | + * following way: while either word1 or word2 are non-empty, choose one of the following |
| 8 | + * options: |
| 9 | + * - If word1 is non-empty, append the first character in word1 to merge and delete it from word1. |
| 10 | + * - For example, if word1 = "abc" and merge = "dv", then after choosing this operation, |
| 11 | + * word1 = "bc" and merge = "dva". |
| 12 | + * - If word2 is non-empty, append the first character in word2 to merge and delete it from word2. |
| 13 | + * - For example, if word2 = "abc" and merge = "", then after choosing this operation, |
| 14 | + * word2 = "bc" and merge = "a". |
| 15 | + * |
| 16 | + * Return the lexicographically largest merge you can construct. |
| 17 | + * |
| 18 | + * A string a is lexicographically larger than a string b (of the same length) if in the first |
| 19 | + * position where a and b differ, a has a character strictly larger than the corresponding |
| 20 | + * character in b. For example, "abcd" is lexicographically larger than "abcc" because the |
| 21 | + * first position they differ is at the fourth character, and d is greater than c. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} word1 |
| 26 | + * @param {string} word2 |
| 27 | + * @return {string} |
| 28 | + */ |
| 29 | +var largestMerge = function(word1, word2) { |
| 30 | + let merge = ''; |
| 31 | + let i = 0; |
| 32 | + let j = 0; |
| 33 | + |
| 34 | + while (i < word1.length && j < word2.length) { |
| 35 | + if (word1.slice(i) >= word2.slice(j)) { |
| 36 | + merge += word1[i++]; |
| 37 | + } else { |
| 38 | + merge += word2[j++]; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + merge += word1.slice(i) + word2.slice(j); |
| 43 | + return merge; |
| 44 | +}; |
0 commit comments