-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path07_Lexicographically_Minimum_String_After_Removing_Stars.cpp
More file actions
83 lines (61 loc) · 2.26 KB
/
Copy path07_Lexicographically_Minimum_String_After_Removing_Stars.cpp
File metadata and controls
83 lines (61 loc) · 2.26 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// 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.
// Example 1:
// Input: s = "aaba*"
// Output: "aab"
// Explanation:
// We should delete one of the 'a' characters with '*'. If we choose s[3], s becomes the lexicographically smallest.
// Example 2:
// Input: s = "abc"
// Output: "abc"
// Explanation:
// There is no '*' in the string.
// Constraints:
// 1 <= s.length <= 105
// s consists only of lowercase English letters and '*'.
// The input is generated such that it is possible to delete all '*' characters.
class Solution
{
public:
string clearStars(string s)
{
vector<vector<int>> pos(26);
priority_queue<char, vector<char>, greater<char>> pq;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '*')
{
char c = pq.top();
s[pos[c - 'a'].back()] = '*';
pos[c - 'a'].pop_back();
if (pos[c - 'a'].empty())
pq.pop();
}
else
{
if (pos[s[i] - 'a'].empty())
pq.push(s[i]);
pos[s[i] - 'a'].push_back(i);
}
}
string res;
for (char c : s)
if (c >= 'a')
res += c;
return res;
}
};
/*
Code Explanation:
1. We create a vector of vectors 'pos' to store positions of each character (a-z).
2. Use min heap priority queue to always get smallest character.
3. Iterate through string:
- If '*' found: Get smallest char from pq, mark its leftmost position as '*', update positions
- If letter found: Store its position and add to pq if first occurrence
4. Finally create result string with remaining non-'*' characters
Time Complexity: O(n log k) where n is string length, k is unique characters
Space Complexity: O(n) for storing positions and priority queue
*/