|
| 1 | +/** |
| 2 | + * [1663] Smallest String With A Given Numeric Value |
| 3 | + * |
| 4 | + * 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. |
| 5 | + * 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. |
| 6 | + * You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. |
| 7 | + * 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. |
| 8 | + * |
| 9 | + * Example 1: |
| 10 | + * |
| 11 | + * Input: n = 3, k = 27 |
| 12 | + * Output: "aay" |
| 13 | + * Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * Input: n = 5, k = 73 |
| 18 | + * Output: "aaszz" |
| 19 | + * |
| 20 | + * |
| 21 | + * Constraints: |
| 22 | + * |
| 23 | + * 1 <= n <= 10^5 |
| 24 | + * n <= k <= 26 * n |
| 25 | + * |
| 26 | + */ |
| 27 | +pub struct Solution {} |
| 28 | + |
| 29 | +// problem: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ |
| 30 | +// discuss: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/discuss/?currentPage=1&orderBy=most_votes&query= |
| 31 | + |
| 32 | +// submission codes start here |
| 33 | + |
| 34 | +impl Solution { |
| 35 | + pub fn get_smallest_string(n: i32, k: i32) -> String { |
| 36 | + let mut result: Vec<char> = vec!['a'; n as usize]; |
| 37 | + let mut idx: usize = n as usize - 1; |
| 38 | + let mut value = k - n; |
| 39 | + while value > 25 { |
| 40 | + result[idx] = 'z'; |
| 41 | + idx -= 1; |
| 42 | + value -= 25; |
| 43 | + } |
| 44 | + result[idx] = (value as u8 + 'a' as u8) as char; |
| 45 | + result.into_iter().collect::<String>() |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// submission codes end |
| 50 | + |
| 51 | +#[cfg(test)] |
| 52 | +mod tests { |
| 53 | + use super::*; |
| 54 | + |
| 55 | + #[test] |
| 56 | + fn test_1663_example_1() { |
| 57 | + let n = 3; |
| 58 | + let k = 27; |
| 59 | + |
| 60 | + let result = "aay".to_string(); |
| 61 | + |
| 62 | + assert_eq!(Solution::get_smallest_string(n, k), result); |
| 63 | + } |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn test_1663_example_2() { |
| 67 | + let n = 5; |
| 68 | + let k = 73; |
| 69 | + |
| 70 | + let result = "aaszz".to_string(); |
| 71 | + |
| 72 | + assert_eq!(Solution::get_smallest_string(n, k), result); |
| 73 | + } |
| 74 | +} |
0 commit comments