[LeetCode] Lexicographically Smallest String After Operations With Constraint

3106. Lexicographically Smallest String After Operations With Constraint

You are given a string s and an integer k.

Define a function distance(s1, s2) between two strings s1 and s2 of the same length n as:

  • The sum of the minimum distance between s1[i] and s2[i] when the characters from 'a' to 'z' are placed in a cyclic order, for all i in the range [0, n - 1].

For example, distance("ab", "cd") == 4, and distance("a", "z") == 1.

You can change any letter of s to any other lowercase English letter, any number of times.

Return a string denoting the lexicographically smallest string t you can get after some changes, such that distance(s, t) <= k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string getSmallestString(string s, int k) {
for(int i = 0; i < s.length() and k; i++) {
for(char ch = 'a'; ch <= 'z'; ch++) {
int now = abs(s[i] - ch);
int mi = min(now, 26 - now);
if(mi <= k) {
k -= mi;
s[i] = ch;
break;
}
}
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/09/PS/LeetCode/lexicographically-smallest-string-after-operations-with-constraint/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.