3816. Lexicographically Smallest String After Deleting Duplicate Characters
Description
You are given a string s that consists of lowercase English letters.
You can perform the following operation any number of times (possibly zero times):
- Choose any letter that appears at least twice in the current string
sand delete any one occurrence.
Return the lexicographically smallest resulting string that can be formed this way.
Β
Example 1:
Input: s = "aaccb"
Output: "aacb"
Explanation:
We can form the strings "acb", "aacb", "accb", and "aaccb". "aacb" is the lexicographically smallest one.
For example, we can obtain "aacb" by choosing 'c' and deleting its first occurrence.
Example 2:
Input: s = "z"
Output: "z"
Explanation:
We cannot perform any operations. The only string we can form is "z".
Β
Constraints:
1 <= s.length <= 105scontains lowercase English letters only.
Solutions
Solution 1: Monotonic Stack
We can use a stack \(\textit{stk}\) to store the characters of the result string, and a hash table \(\textit{cnt}\) to record the number of occurrences of each character in string \(s\).
First, we initialize \(\textit{cnt}\) to count the occurrences of each character in string \(s\). Then, we iterate through each character \(c\) in string \(s\):
- If the stack is not empty, the top character of the stack is greater than \(c\), and the top character will appear again in string \(s\), we pop the top character and decrement its count in \(\textit{cnt}\).
- Push character \(c\) into the stack.
Finally, if there are duplicate characters in the stack, we continue to pop the top character until the count of the top character in \(\textit{cnt}\) is 1.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string \(s\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |