LeetCode 1754. Largest Merge Of Two Strings
Greedy
You are given two strings word1
and word2
. You want to construct a string merge
in the following way: while either word1
or word2
are non-empty, choose one of the following options:
If
word1
is non-empty, append the first character inword1
tomerge
and delete it fromword1
.For example, if
word1 = "abc"
andmerge = "dv"
, then after choosing this operation,word1 = "bc"
andmerge = "dva"
.
If
word2
is non-empty, append the first character inword2
tomerge
and delete it fromword2
.For example, if
word2 = "abc"
andmerge = ""
, then after choosing this operation,word2 = "bc"
andmerge = "a"
.
Return the lexicographically largest merge
you can construct.
A string a
is lexicographically larger than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly larger than the corresponding character in b
. For example, "abcd"
is lexicographically larger than "abcc"
because the first position they differ is at the fourth character, and d
is greater than c
.
Example 1:
Example 2:
Constraints:
1 <= word1.length, word2.length <= 3000
word1
andword2
consist only of lowercase English letters.
Solution:
A short version
A faster version
Last updated