[InterviewBit] Maximal String

Maximal String

  • Time :
  • Space :
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
string Solution::solve(string A, int B) {
string s = A;
sort(rbegin(s), rend(s));
string res = "";
unordered_map<char, vector<char>> mp;
unordered_map<char, int> freq;
for(int i = 0; i < A.size(); i++) {
if(s[i] == A[i]) res.push_back(s[i]);
else if(s[i] > A[i] and B) {
B -= 1;
res.push_back(s[i]);
mp[s[i]].push_back(A[i]);
freq[s[i]]++;
} else {
vector<char>& now = mp[A[i]];
sort(begin(now), end(now));
while(freq[now.back()]) {
freq[now.back()]--;
char b = now.back(); now.pop_back();
if(b != A[i]) {
sort(begin(mp[b]), end(mp[b]));
now.push_back(mp[b].back());
mp[b].pop_back();
sort(begin(now), end(now));
}
}
res.push_back(now.back());
now.pop_back();
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/02/PS/interviewbit/maximal-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.