-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
More file actions
49 lines (42 loc) · 1.34 KB
/
2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
File metadata and controls
49 lines (42 loc) · 1.34 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 2434. Using a Robot to Print the Lexicographically Smallest String
* https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {string} s
* @return {string}
*/
var robotWithString = function(s) {
const charCount = Array(26).fill(0);
for (const char of s) {
charCount[char.charCodeAt(0) - 97]++;
}
const stack = [];
let minCharIndex = 0;
let result = '';
for (const char of s) {
stack.push(char);
charCount[char.charCodeAt(0) - 97]--;
while (minCharIndex < 26 && charCount[minCharIndex] === 0) {
minCharIndex++;
}
while (stack.length
&& (minCharIndex === 26 || stack[stack.length - 1].charCodeAt(0) - 97 <= minCharIndex)) {
result += stack.pop();
}
}
while (stack.length) {
result += stack.pop();
}
return result;
};