[LeetCode] Lexicographically Minimum String After Removing Stars

3170. Lexicographically Minimum String After Removing Stars

You are given a string s. It may contain any number of '*' characters. Your task is to remove all '*' characters.

While there is a '*', do the following operation:

  • Delete the leftmost '*' and the smallest non-'*' character to its left. If there are several smallest characters, you can delete any of them.

Return the lexicographically smallest resulting string after removing all '*' characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string clearStars(string s) {
map<char,vector<int>> mp;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '*') {
if(mp.size()) {
begin(mp)->second.pop_back();
if(begin(mp)->second.empty()) mp.erase(begin(mp));
}
} else mp[s[i]].push_back(i);
}
vector<pair<int,char>> S;
for(auto& [ch, ord] : mp) {
for(auto& p : ord) S.push_back({p,ch});
}
sort(begin(S), end(S));
string res = "";
for(auto& [_,ch] : S) res.push_back(ch);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/02/PS/LeetCode/lexicographically-minimum-string-after-removing-stars/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.