题解:
每次从word1 和 word2 中取首字符 添加到merge字符串中,使得merge字符串字典序最大
- 比较word1 和 word2 的首字符,谁大用谁的
- 如果word1 和 word2 的首字符相等,此时需要比较word1 和 word2的字典序谁大,优先取字典序大的那个
class Solution {
public String largestMerge(String word1, String word2) {
int l1 = word1.length();
int l2 = word2.length();
char[] res = new char[l1 + l2];
char[] w1 = word1.toCharArray();
char[] w2 = word2.toCharArray();
int i = 0, j = 0, k = 0;
while (i < l1 && j < l2) {
if (w1[i] > w2[j]) res[k++] = w1[i++];
else if (w1[i] < w2[j]) {
res[k++] = w2[j++];
} else {
if (word1.substring(i).compareTo(word2.substring(j)) > 0) {
res[k++] = w1[i++];
} else {
res[k++] = w2[j++];
}
} ;
}
while (i < l1) res[k++] = w1[i++];
while (j < l2) res[k++] = w2[j++];
return new String(res);
}
}
标签:++,res,word1,w2,w1,word2,字符串,1754,字典
From: https://www.cnblogs.com/eiffelzero/p/17002756.html