LeetCode 1754: Largest Merge Of Two Strings
Problem Description
Explanation:
To solve this problem, we can use a greedy approach. We compare the current characters of word1
and word2
, and choose the larger character to append to the merge
string. If the characters are equal, we compare the following characters until we find a difference.
We iterate through the strings until one of them becomes empty, and then append the remaining characters of the non-empty string to the merge
string.
Solution:
Solutions
class Solution {
public String largestMerge(String word1, String word2) {
StringBuilder merge = new StringBuilder();
while (!word1.isEmpty() && !word2.isEmpty()) {
if (word1.compareTo(word2) > 0) {
merge.append(word1.charAt(0));
word1 = word1.substring(1);
} else {
merge.append(word2.charAt(0));
word2 = word2.substring(1);
}
}
merge.append(word1).append(word2);
return merge.toString();
}
}
Loading editor...