[LeetCode] Using a Robot to Print the Lexicographically Smallest String

2434. Using a Robot to Print the Lexicographically Smallest String

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 s and give it to the robot. The robot will append this character 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.

Return the lexicographically smallest string that can be written on the paper.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
string robotWithString(string s) {
unordered_map<char, int> freq;
for(auto ch : s) freq[ch]++;
string t = "";
string res = "";
for(int i = 0; i < s.length(); i++) {
t.push_back(s[i]);
freq[s[i]]--;
bool has = false;
while(t.length()) {
bool has = false;
for(char ch = 'a'; ch < t.back() and !has; ch++) {
if(freq[ch]) has = true;
}
if(has) break;
res.push_back(t.back());
t.pop_back();
}
}
while(t.length()) {
bool has = false;
for(char ch = 'a'; ch < t.back() and !has; ch++) {
if(freq[ch]) has = true;
}
if(has) break;
res.push_back(t.back());
t.pop_back();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/09/PS/LeetCode/using-a-robot-to-print-the-lexicographically-smallest-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.