class Solution {
public:
string clearStars(string s) {
// Priority queue of pair<char, int>.
// Primary sorted by char. Smaller chars are first. Secondary sorted by ints. Larger ints are first.
priority_queue<
pair<char, int>,
vector<pair<char, int>>,
decltype([](const pair<char, int>& a, const pair<char, int>& b)
{
if(b.first == a.first)
{
return a.second < b.second;
}
else
{
return a.first > b.first;
}
})
> pq{};
// Iterate s from left to right. If char in s is '*' put the character from pq into
// removedIndexes. These indexes will not be included in returned string. See stringstream ss below.
unordered_set<int> removedIndexes{};
for(int ii=0; ii<s.size(); ++ii)
{
char c = s[ii];
if(c == '*')
{
pair<char, int> top = pq.top();
pq.pop();
removedIndexes.insert(top.second);
}
else
{
pq.push({c, ii});
}
}
// Put in all characters from s into ss except for '*' chars and
// chars that were removed from s (that's removedIndexes).
stringstream ss{};
for(int ii=0; ii<s.size(); ++ii)
{
if (s[ii] == '*')
{
continue;
}
if (removedIndexes.find(ii) == removedIndexes.end())
{
ss << s[ii];
}
}
return ss.str();
}
};