The numeric value of a lowercase character is defined as its position
(1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.
The numeric value of a string consisting of lowercase characters is defined as the sum of its characters’ numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.
You are given two integers n and k. Return thelexicographically smallest string with length equal to n and numeric value equal to
k.
Note that a string x is lexicographically smaller than string y if x
comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.
Input: n =3, k =27Output: "aay"Explanation: The numeric value of the string is1+1+25=27, and it is the smallest string with such a value and length equal to 3.
To get the lexicographically smallest string, fill the string from left to right with ‘a’ as much as possible, and only use larger letters at the end to reach the required sum.
classSolution {
public: string getSmallestString(int n, int k) {
string ans(n, 'a');
k -= n;
for (int i = n-1; i >=0&& k >0; --i) {
int add = min(25, k);
ans[i] += add;
k -= add;
}
return ans;
}
};
classSolution {
public String getSmallestString(int n, int k) {
char[] ans =newchar[n];
Arrays.fill(ans, 'a');
k -= n;
for (int i = n-1; i >= 0 && k > 0; --i) {
int add = Math.min(25, k);
ans[i]+= add;
k -= add;
}
returnnew String(ans);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
fungetSmallestString(n: Int, k: Int): String {
val ans = CharArray(n) { 'a' }
var rem = k - n
var i = n - 1while (i >=0&& rem > 0) {
val add = minOf(25, rem)
ans[i] = (ans[i].code + add).toChar()
rem -= add
i-- }
return String(ans)
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defgetSmallestString(self, n: int, k: int) -> str:
ans = ['a'] * n
k -= n
i = n -1while k >0:
add = min(25, k)
ans[i] = chr(ord('a') + add)
k -= add
i -=1return''.join(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnget_smallest_string(n: i32, k: i32) -> String {
letmut ans =vec![b'a'; n asusize];
letmut k = k - n;
letmut i = n asusize;
while k >0 {
i -=1;
let add = k.min(25);
ans[i] += add asu8;
k -= add;
}
String::from_utf8(ans).unwrap()
}
}