Leetcode 482. License Key Formatting

Problem

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.

Algorithm

Count from back to front, then concatenate the reversed character groups in reverse order.

Code

class Solution:
    def licenseKeyFormatting(self, s: str, k: int) -> str:
        rs = s[::-1]
        slen = len(rs)
        cnts, buf, subans = 0, "", []
        for i in range(slen):
            if rs[i] >= '0' and rs[i] <= '9' or rs[i] >= 'A' and rs[i] <= 'Z':
                buf += rs[i]
                cnts += 1
            elif rs[i] >= 'a' and rs[i] <= 'z':
                buf += rs[i].upper()
                cnts += 1
            if cnts == k:
                subans.append(buf)
                cnts = 0
                buf = ""
        
        if buf:
            subans.append(buf)
        
        ans = '-'.join(part[::-1] for part in reversed(subans))

        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值