diff options
author | Jack Sangdahl <[email protected]> | 2025-06-05 18:44:21 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-06-05 18:44:21 -0600 |
commit | 79c7e9462c5cb51657167f9412b5c3711a5d8a61 (patch) | |
tree | cbdd0787d3518d390c497a6d8e1e1117ed14af10 /using_robot_print_lex_small_str.py | |
parent | a05784326180667fd695dd35d97dce314ab0a31c (diff) | |
download | leetcode-79c7e9462c5cb51657167f9412b5c3711a5d8a61.tar.gz leetcode-79c7e9462c5cb51657167f9412b5c3711a5d8a61.zip |
2434. using a robot to print the lexicographically smallest string
Diffstat (limited to 'using_robot_print_lex_small_str.py')
-rw-r--r-- | using_robot_print_lex_small_str.py | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/using_robot_print_lex_small_str.py b/using_robot_print_lex_small_str.py new file mode 100644 index 0000000..3189464 --- /dev/null +++ b/using_robot_print_lex_small_str.py @@ -0,0 +1,35 @@ +# 2434. Using a Robot to Print the Lexicographically Smallest String +from collections import Counter + +""" +you are given a string 's' and a robot that currently holds an empty string +'t'. apply one of the followiing operations until 's' and 't' are both empty. +remove the first character of a string 's' and give it to the robot. the +robot will append this charcter to the string 't'. remove the last character +of a string 't' and give it to the robot. the robot will write this character +on paper. +""" + + +class Solution(object): + def robotWithString(self, s): + """ + :type s: str + :rtype: str + """ + cnt, low, ans, t = Counter(s), "a", [], [] + for i in s: + t += i + cnt[i] -= 1 + while low < "z" and cnt[low] == 0: + low = chr(ord(low) + 1) + while t and t[-1] <= low: + ans += t.pop() + return "".join(ans) + + +if __name__ == "__main__": + obj = Solution() + print(obj.robotWithString(s="zza")) + print(obj.robotWithString(s="bac")) + print(obj.robotWithString(s="bdda")) |