class Solution:
def largestMerge(self, word1: str, word2: str) -> str:
i, j = 0, 0
merge = []
while i < len(word1) and j < len(word2):
if word1[i:] > word2[j:]:
merge.append(word1[i])
i += 1
else:
merge.append(word2[j])
j += 1
merge.append(word1[i:])
merge.append(word2[j:])
return ''.join(merge)
class Solution {
public:
string largestMerge(string word1, string word2) {
int i = 0, j = 0;
string merge = "";
int n1 = word1.size(), n2 = word2.size();
while (i < n1 && j < n2) {
if (word1.substr(i) > word2.substr(j)) {
merge += word1[i++];
} else {
merge += word2[j++];
}
}
merge += word1.substr(i);
merge += word2.substr(j);
return merge;
}
};
class Solution {
public String largestMerge(String word1, String word2) {
int i = 0, j = 0;
StringBuilder merge = new StringBuilder();
while (i < word1.length() && j < word2.length()) {
if (word1.substring(i).compareTo(word2.substring(j)) > 0) {
merge.append(word1.charAt(i++));
} else {
merge.append(word2.charAt(j++));
}
}
merge.append(word1.substring(i));
merge.append(word2.substring(j));
return merge.toString();
}
}
var largestMerge = function(word1, word2) {
let i = 0, j = 0;
let merge = "";
while (i < word1.length && j < word2.length) {
if (word1.slice(i) > word2.slice(j)) {
merge += word1[i++];
} else {
merge += word2[j++];
}
}
merge += word1.slice(i);
merge += word2.slice(j);
return merge;
};
word1
and word2
, you are to create a new string called the "largest merge" by merging the two input strings together. At each step, you choose either the first character of word1
or word2
to append to the result, then remove that character from its original string. You repeat this process until both strings are empty. The goal is to construct the lexicographically largest possible string (i.e., the string that would come last in dictionary order). Each character from each input string must be used exactly once, and you cannot reuse characters.
word1
is lexicographically larger than the remaining part of word2
, then taking from word1
will help us make the merge as large as possible, and vice versa.
word1
and word2
.word1
's remaining substring is lexicographically greater, we take its first character and move its pointer forward.word2
and move its pointer.word1 = "cabaa"
and word2 = "bcaaa"
.word1
: merge = "c"word2
: merge = "cb"word2
: merge = "cbc"word1
: merge = "cbca"word1
: merge = "cbcab"word2
: merge = "cbcaba"word2
: merge = "cbcabaa"word1
: merge = "cbcabaaa"word2
: merge = "cbcabaaaa"word1
, append it: merge = "cbcabaaaaa""cbcabaaaaa"
word1
and word2
.