Skip to content

Commit 8dbb2ee

Browse files
authored
Create 2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
1 parent ead41a9 commit 8dbb2ee

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
const ord = (c) => c.charCodeAt();
3+
const char = (ascii) => String.fromCharCode(ascii);
4+
/**
5+
* @param {string} s
6+
* @return {string}
7+
*/
8+
9+
const robotWithString = (s) => {
10+
let f = Array(26).fill(0), t = [], res = '';
11+
for (const c of s) f[ord(c) - 97]++;
12+
for (const c of s) {
13+
f[ord(c) - 97]--;
14+
t.push(c);
15+
while (t.length) {
16+
let find = false;
17+
for (let i = 0; i < 26; i++) {
18+
let curC = char(i + 97);
19+
if (curC < t[t.length - 1]) { // check if can find smaller char < t's last char, in the rest of S
20+
if (f[i] > 0) {
21+
find = true;
22+
break;
23+
}
24+
}
25+
}
26+
if (find) { // find means there is lexical smaller one, by moving much more right
27+
break;
28+
} else { // not find, current is lexical smaller
29+
res += t.pop();
30+
}
31+
}
32+
}
33+
return res;
34+
};

0 commit comments

Comments
 (0)