https://leetcode.com/problems/largest-merge-of-two-strings/
给定两个字符串 s 1 s_1 s1和 s 2 s_2 s2,从一个空串 s s s开始,开两个指针 i = j = 0 i=j=0 i=j=0,每一步可以将 s 1 [ i ] s_1[i] s1[i]或 s 2 [ j ] s_2[j] s2[j]添到 s s s后面,同时 i i i或 j j j向后挪动一位。问最后得到的最大字典序的 s s s是什么。
如果
s
1
[
i
]
>
s
2
[
j
]
s_1[i]>s_2[j]
s1[i]>s2[j],那么显然应该添
s
1
[
i
]
s_1[i]
s1[i];反之如果
s
1
[
i
]
<
s
2
[
j
]
s_1[i]
class Solution {
public:
string largestMerge(string s1, string s2) {
string s;
for (int i = 0, j = 0; i < s1.size() || j < s2.size();)
s += bigger(s1, s2, i, j) ? s1[i++] : s2[j++];
return s;
}
bool bigger(string& s1, string& s2, int i, int j) {
while (i < s1.size() && j < s2.size()) {
if (s1[i] > s2[j]) return true;
else if (s1[i] < s2[j]) return false;
else i++, j++;
}
return j == s2.size();
}
};
时间复杂度 O ( min { l s 1 , l s 2 } ( l s 1 + l s 2 ) ) O(\min\{l_{s_1},l_{s_2}\}(l_{s_1}+l_{s_2})) O(min{ls1,ls2}(ls1+ls2)),空间 O ( 1 ) O(1) O(1)。