Skip to content

Commit bd01bb0

Browse files
committed
Sync LeetCode submission Runtime - 498 ms (76.98%), Memory - 23.5 MB (73.38%)
1 parent 91a51e9 commit bd01bb0

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<p>You are given a string <code>s</code>. It may contain any number of <code>&#39;*&#39;</code> characters. Your task is to remove all <code>&#39;*&#39;</code> characters.</p>
2+
3+
<p>While there is a <code>&#39;*&#39;</code>, do the following operation:</p>
4+
5+
<ul>
6+
<li>Delete the leftmost <code>&#39;*&#39;</code> and the <strong>smallest</strong> non-<code>&#39;*&#39;</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
7+
</ul>
8+
9+
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>&#39;*&#39;</code> characters.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
14+
<div class="example-block">
15+
<p><strong>Input:</strong> <span class="example-io">s = &quot;aaba*&quot;</span></p>
16+
17+
<p><strong>Output:</strong> <span class="example-io">&quot;aab&quot;</span></p>
18+
19+
<p><strong>Explanation:</strong></p>
20+
21+
<p>We should delete one of the <code>&#39;a&#39;</code> characters with <code>&#39;*&#39;</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
22+
</div>
23+
24+
<p><strong class="example">Example 2:</strong></p>
25+
26+
<div class="example-block">
27+
<p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p>
28+
29+
<p><strong>Output:</strong> <span class="example-io">&quot;abc&quot;</span></p>
30+
31+
<p><strong>Explanation:</strong></p>
32+
33+
<p>There is no <code>&#39;*&#39;</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
34+
</div>
35+
36+
<p>&nbsp;</p>
37+
<p><strong>Constraints:</strong></p>
38+
39+
<ul>
40+
<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
41+
<li><code>s</code> consists only of lowercase English letters and <code>&#39;*&#39;</code>.</li>
42+
<li>The input is generated such that it is possible to delete all <code>&#39;*&#39;</code> characters.</li>
43+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Approach: Greedy
2+
3+
class Solution:
4+
def clearStars(self, s: str) -> str:
5+
cnt = [[] for _ in range(26)]
6+
arr = list(s)
7+
8+
for i, c in enumerate(arr):
9+
if c != '*':
10+
cnt[ord(c) - ord('a')].append(i)
11+
else:
12+
for j in range(26):
13+
if cnt[j]:
14+
arr[cnt[j].pop()] = '*'
15+
break
16+
17+
return ''.join(c for c in arr if c != '*')
18+

0 commit comments

Comments
 (0)