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

你可能感兴趣的:(Leetcode,解题报告,leetcode,linux,算法)