- 密钥格式化
给定一个许可密钥字符串 s,仅由字母、数字字符和破折号组成。字符串由 n 个破折号分成 n + 1 组。你也会得到一个整数 k 。
我们想要重新格式化字符串 s,使每一组包含 k 个字符,除了第一组,它可以比 k 短,但仍然必须包含至少一个字符。此外,两组之间必须插入破折号,并且应该将所有小写字母转换为大写字母。
返回 重新格式化的许可密钥 。
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.
We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
Return the reformatted license key.
示例 1:
输入:S = "5F3Z-2e-9-w", k = 4
输出:"5F3Z-2E9W"
解释:字符串 S 被分成了两个部分,每部分 4 个字符;
注意,两个额外的破折号需要删掉。
示例 2:
输入:S = "2-5g-3-J", k = 2
输出:"2-5G-3J"
解释:字符串 S 被分成了 3 个部分,按照前面的规则描述,第一部分的字符可以少于给定的数量,其余部分皆为 2 个字符。
Example 1:
Input: s = "5F3Z-2e-9-w", k = 4
Output: "5F3Z-2E9W"
Explanation: The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: s = "2-5g-3-J", k = 2
Output: "2-5G-3J"
Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
var licenseKeyFormatting = function (s, k) {
let len = s.length
let arr = []
let cur = 0
for (let i = len - 1; i >= 0; i--) {
if (s[i] !== '-') {
cur++
arr.push(s[i].toUpperCase())
if (cur % k == 0) {
arr.push('-')
}
}
}
if (arr.length > 0 && arr[arr.length - 1] === '-') arr.pop()
return arr.reverse().join('');
};
var licenseKeyFormatting = function (s, k) {
let len = s.length
let arr = []
let cur = 0
for (let i = len - 1; i >= 0; i--) {
if (s[i] !== '-') {//只对数字,字母进行操作
cur++//为字母数字的下标
arr.push(s[i].toUpperCase()//将字母或数字进行大写转换并添加到新数组里面
if (cur % k == 0) {//当对k取余为0时,这个长度为k已经完成,需要用-分隔
arr.push('-')
}
}
}
//当新数组的最后一项为短横线时,去掉短横线
if (arr.length > 0 && arr[arr.length - 1] === '-') arr.pop()
return arr.reverse().join('');
};
leetcode:https://leetcode.cn/problems/license-key-formatting/description/