1
+ package medium
2
+
3
+ import GreedyTopic
4
+ import StringTopic
5
+
6
+
7
+ /* *
8
+ * 1663. Smallest String With A Given Numeric Value
9
+ * https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/
10
+ *
11
+ The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet,
12
+ 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.
13
+
14
+ The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values.
15
+ For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.
16
+
17
+ You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.
18
+
19
+ Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is,
20
+ 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.
21
+ */
22
+
23
+ class Medium1663 : StringTopic , GreedyTopic {
24
+
25
+ fun getSmallestString (n : Int , k : Int ): String {
26
+ val sb = StringBuilder ()
27
+ var kk = k
28
+ for (i in n - 1 downTo 0 ) {
29
+ val rem = kk - 26 * i
30
+ if (rem <= 0 ) {
31
+ sb.append(' a' )
32
+ -- kk
33
+ } else {
34
+ sb.append((' a' .toInt() + rem - 1 ).toChar())
35
+ kk - = rem
36
+ }
37
+ }
38
+ return sb.toString()
39
+ }
40
+ }
41
+
42
+ fun main () {
43
+ println (Medium1663 ().getSmallestString(3 , 27 ))
44
+ println (Medium1663 ().getSmallestString(5 , 73 ))
45
+ }
0 commit comments