Description
You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty:
- Remove the first character of a string
sand give it to the robot. The robot will append this character to the stringt. - Remove the last character of a string
tand give it to the robot. The robot will write this character on paper.
Return the lexicographically smallest string that can be written on the paper.
Example 1:
Input: s = "zza" Output: "azz" Explanation: Let p denote the written string. Initially p="", s="zza", t="". Perform first operation three times p="", s="", t="zza". Perform second operation three times p="azz", s="", t="".
Example 2:
Input: s = "bac" Output: "abc" Explanation: Let p denote the written string. Perform first operation twice p="", s="c", t="ba". Perform second operation twice p="ab", s="c", t="". Perform first operation p="ab", s="", t="c". Perform second operation p="abc", s="", t="".
Example 3:
Input: s = "bdda" Output: "addb" Explanation: Let p denote the written string. Initially p="", s="bdda", t="". Perform first operation four times p="", s="", t="bdda". Perform second operation four times p="addb", s="", t="".
Constraints:
1 <= s.length <= 105sconsists of only English lowercase letters.
Solutions
Solution 1: Greedy + Stack
The problem can be transformed into: given a string sequence, use an auxiliary stack to convert it into the lexicographically smallest string sequence.
We can use an array cnt to maintain the count of each character in string s, use a stack stk as the auxiliary stack mentioned in the problem, and use a variable mi to keep track of the smallest character not yet traversed in the string.
Traverse the string s. For each character c, first decrement its count in the array cnt and update mi. Then push c onto the stack. At this point, if the top element of the stack is less than or equal to mi, repeatedly pop the top element from the stack and add it to the answer.
After the traversal, return the answer.
The time complexity is O(n + |Σ|), and the space complexity is O(n), where n is the length of the string s and |Σ| is the size of the character set, which is 26 in this problem.
class Solution: def robotWithString(self, s: str) -> str: cnt = Counter(s) ans = [] stk = [] mi = 'a' for c in s: cnt[c] -= 1 while mi < 'z' and cnt[mi] == 0: mi = chr(ord(mi) + 1) stk.append(c) while stk and stk[-1] <= mi: ans.append(stk.pop()) return ''.join(ans)(code-box)
