Skip to content

Commit 2e4b11e

Browse files
authored
Create 3106-lexicographically-smallest-string-after-operations-with-constraint.js
1 parent 49bb420 commit 2e4b11e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @return {string}
5+
*/
6+
const getSmallestString = function(s, k) {
7+
const n = s.length
8+
s = s + s
9+
const a = 'a'.charCodeAt(0)
10+
let res = '', idx = 0
11+
for(let j = 0; j < n; j++) {
12+
for(let i = 0; i < 26; i++) {
13+
const len = chk(a + i, j)
14+
if(len === 0) {
15+
res += s[j]
16+
break
17+
} else if(len && len <= k) {
18+
k -= len
19+
res += String.fromCharCode(a + i)
20+
break
21+
}
22+
}
23+
}
24+
25+
26+
return res
27+
28+
function chk(code, targetIdx) {
29+
const targetCode = s[targetIdx].charCodeAt(0)
30+
if(targetCode > code) {
31+
return Math.min(targetCode - code, code + 26 - targetCode)
32+
} else {
33+
return Math.min(code - targetCode, targetCode + 26 - code)
34+
}
35+
36+
}
37+
};

0 commit comments

Comments
 (0)