Skip to content

Commit 61ea902

Browse files
authored
Update 2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
1 parent a9765ac commit 61ea902

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2434-using-a-robot-to-print-the-lexicographically-smallest-string.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
1+
/**
2+
* @param {string} s
3+
* @return {string}
4+
*/
5+
const robotWithString = function (s) {
6+
const stk = []
7+
const freq = Array(26).fill(0)
8+
const a = 'a'.charCodeAt(0)
9+
for (const ch of s) {
10+
freq[ch.charCodeAt(0) - a]++
11+
}
12+
13+
let res = ''
14+
15+
for (const ch of s) {
16+
stk.push(ch)
17+
freq[ch.charCodeAt(0) - a]--
18+
while (stk.length && stk[stk.length - 1] <= helper(freq)) {
19+
const e = stk.pop()
20+
res += e
21+
}
22+
}
23+
24+
while (stk.length) {
25+
res += stk.pop()
26+
}
27+
28+
return res
29+
30+
function helper(arr) {
31+
const a = 'a'.charCodeAt(0)
32+
for (let i = 0; i < 26; i++) {
33+
if (arr[i] !== 0) return String.fromCharCode(a + i)
34+
}
35+
36+
return ''
37+
}
38+
}
39+
40+
41+
// another
142

243
const ord = (c) => c.charCodeAt();
344
const char = (ascii) => String.fromCharCode(ascii);

0 commit comments

Comments
 (0)