Description
You are given a string s
.
Consider performing the following operation until s
becomes empty:
- For every alphabet character from
'a'
to'z'
, remove the first occurrence of that character ins
(if it exists).
For example, let initially s = "aabcbbca"
. We do the following operations:
- Remove the underlined characters
s = "aabcbbca"
. The resulting string iss = "abbca"
. - Remove the underlined characters
s = "abbca"
. The resulting string iss = "ba"
. - Remove the underlined characters
s = "ba"
. The resulting string iss = ""
.
Return the value of the string s
right before applying the last operation. In the example above, answer is "ba"
.
Example 1:
Input: s = "aabcbbca" Output: "ba" Explanation: Explained in the statement.
Example 2:
Input: s = "abcd" Output: "abcd" Explanation: We do the following operation: - Remove the underlined characters s = "abcd". The resulting string is s = "". The string just before the last operation is "abcd".
Constraints:
1 <= s.length <= 5 * 105
s
consists only of lowercase English letters.
Solution
Python3
class Solution:
def lastNonEmptyString(self, s: str) -> str:
N = len(s)
count = [0] * 26
A = [-1] * N
def f(x):
return ord(x) - ord('a')
for i, x in enumerate(s):
A[i] = count[f(x)]
count[f(x)] += 1
MAX = max(count)
res = []
for i, x in enumerate(s):
if A[i] == MAX - 1:
res.append(x)
return "".join(res)