We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
小写字符 的 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1 ,b 的数值为 2 ,c 的数值为 3 ,以此类推。
字符串由若干小写字符组成,字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8 。
给你两个整数 n 和 k 。返回 长度 等于 n 且 数值 等于 k 的 字典序最小 的字符串。
注意,如果字符串 x 在字典排序中位于 y 之前,就认为 x 字典序比 y 小,有以下两种情况:
输入:n = 3, k = 27 输出:"aay" 解释:字符串的数值为 1 + 1 + 25 = 27,它是数值满足要求且长度等于 3 字典序最小的字符串。
输入:n = 5, k = 73 输出:"aaszz"
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/smallest-string-with-a-given-numeric-value 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered:
从后往前填充即可, 因为时间紧,所有没有进行优化。
func getSmallestString(n int, k int) string { var slice []byte for i := 0; i < n; i++ { slice = append(slice, 'a') } var sum int endZ := len(slice) for { sum = getStringSum(slice) if sum == k { break } else if sum < k { mod := (k - sum)/ 26 for mod > 0 { slice[endZ-1] = 'z' endZ-- mod-- } if slice[endZ-1] == 'z' { endZ-- } //这里可以优化的 slice[endZ-1]++ } } return string(slice) } func getStringSum(s []byte) int { var sum int for _, v := range s { sum += (int(v)-'a')+1 } return sum }
Sorry, something went wrong.
No branches or pull requests
小写字符 的 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1 ,b 的数值为 2 ,c 的数值为 3 ,以此类推。
字符串由若干小写字符组成,字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8 。
给你两个整数 n 和 k 。返回 长度 等于 n 且 数值 等于 k 的 字典序最小 的字符串。
注意,如果字符串 x 在字典排序中位于 y 之前,就认为 x 字典序比 y 小,有以下两种情况:
示例 1:
示例 2:
提示:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-string-with-a-given-numeric-value
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered: