-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathlexicographically-smallest-permutation-greater-than-target.cpp
More file actions
52 lines (50 loc) · 1.33 KB
/
lexicographically-smallest-permutation-greater-than-target.cpp
File metadata and controls
52 lines (50 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Time: O(26 * n)
// Space: O(26)
// freq table, greedy
class Solution {
public:
string lexGreaterPermutation(string s, string target) {
const auto& nxt = [](auto& cnt, int x) {
for (int i = (x - 'a') + 1; i < size(cnt); ++i) {
if (!cnt[i]) {
continue;
}
return static_cast<char>('a' + i);
}
return ' ';
};
vector<int> cnt(26);
for (const auto& x : s) {
++cnt[x - 'a'];
}
vector<int> tmp(cnt);
int j = -1;
for (int i = 0; i < size(target); ++i) {
const auto& y = nxt(tmp, target[i]);
if (y != ' ') {
j = i;
}
if (!tmp[target[i] - 'a']) {
break;
}
--tmp[target[i] - 'a'];
}
string result;
if (j == -1) {
return result;
}
for (int i = 0; i < j; ++i) {
result.push_back(target[i]);
--cnt[target[i] - 'a'];
}
const auto& y = nxt(cnt, target[j]);
result.push_back(y);
--cnt[y - 'a'];
for (int i = 0; i < size(cnt); ++i) {
for (; cnt[i]; --cnt[i]) {
result.push_back('a' + i);
}
}
return result;
}
};