3106. 满足距离约束且字典序最小的字符串

满足距离约束且字典序最小的字符串

解法一: 贪心

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func getSmallestString(s string, k int) string {
bytes := []byte(s)
n := len(bytes)
for i := 0; i < n; i++ {
distance := int(min(bytes[i]-'a', 'z'-bytes[i]+1))
if distance > k {
bytes[i] -= byte(k)
break
}
bytes[i] = 'a'
k -= distance
}
return string(bytes)
}
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public String getSmallestString(String s, int k) {
char[] chars = s.toCharArray();
int n = chars.length;
for (int i = 0; i < n; i++) {
int distance = Math.min(chars[i] - 'a', 'z' - chars[i] + 1);
if (distance > k) {
chars[i] -= k;
break;
}
chars[i] = 'a';
k -= distance;
}
return String.valueOf(chars);
}
}
作者

wuhunyu

发布于

2024-07-27

更新于

2025-01-15

许可协议