LeetCode 3106 满足距离约束且字典序最小的字符串
class Solution:
def getSmallestString(self, s: str, k: int) -> str:
ans = list(s); res = ord('a')
for i, x in enumerate(map(ord, ans)):
cnt = min(x - res, res + 26 - x)
if k < cnt:
ans[i] = chr(x - k); break
ans[i] = 'a'; k -= cnt
return "".join(ans)
- String.toCharArray() 将字符串转为字符数组
class Solution {
public String getSmallestString(String s, int k) {
char[] ans = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
int cnt = Math.min(ans[i] - 97, 123 - ans[i]);
if (k < cnt) {
ans[i] -= k; break;
}
ans[i] = 'a'; k -= cnt;
}
return new String(ans);
}
}
标签:cnt,27,07,int,res,2024,ans,String
From: https://www.cnblogs.com/XuGui/p/18327308