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.
Each time we see a * in the string, we must remove the lexicographically smallest non-star character to its left.
To do this, we use a min-heap to track each non-star character and its index.
When a * is found, we mark the smallest such character (by index) for deletion in a map.
Finally, we build the result string by skipping all characters marked for deletion and all * characters.
classSolution {
funclearStars(s: String): String {
val n = s.length
val posStack = Array(26) { ArrayDeque<Int>() }
val arr = s.toCharArray()
for (i in0 until n) {
if (arr[i] !='*') {
posStack[arr[i] - 'a'].addFirst(i)
} else {
for (j in0 until 26) {
if (posStack[j].isNotEmpty()) {
arr[posStack[j].removeFirst()] = '*'break }
}
}
}
val ans = StringBuilder()
for (c in arr) {
if (c !='*') ans.append(c)
}
return ans.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defclearStars(self, s: str) -> str:
n = len(s)
pos_stack = [[] for _ in range(26)]
arr = list(s)
for i, c in enumerate(arr):
if c !='*':
pos_stack[ord(c) - ord('a')].append(i)
else:
for j in range(26):
if pos_stack[j]:
arr[pos_stack[j].pop()] ='*'break ans = [c for c in arr if c !='*']
return''.join(ans)
⏰ Time complexity: - O(n * 26) = O(n). For each character in the string, we may check up to 26 stacks (one for each lowercase letter) when processing a *. Since 26 is a constant, this is effectively O(n).
🧺 Space complexity: O(n). We use up to 26 stacks to store indices, and an array to store the modified string, both of which require O(n) space in the worst case.