Problem Link

Description


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.

Solution


Python3

class Solution:
    def clearStars(self, s: str) -> str:
        N = len(s)
        A = [[] for _ in range(26)]
        
        for i, x in enumerate(s):
            if x == '*':
                for k in range(26):
                    if len(A[k]) != 0:
                        A[k].pop()
                        break
            else:
                A[ord(x) - ord('a')].append(i)
        
        res = ["" for _ in range(N)]
        for k in range(26):
            for index in A[k]:
                res[index] = chr(ord('a') + k)
        
        return "".join(res)