482. 密钥格式化(javascript)482. License Key Formatting

  1. 密钥格式化
    给定一个许可密钥字符串 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/

官方解题:https://leetcode.cn/problems/license-key-formatting/solutions/1029860/mi-yao-ge-shi-hua-by-leetcode-solution-xnae/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值