License Key Formatting

Problem Id: 482 Difficulty: Easy


Intuition

Solution


class Solution:
    def licenseKeyFormatting(self, S: str, K: int) -> str:
        length = 0
        for c in S:
            if c == '-':
                continue
            length += 1

        s = []
        left = length % K
        if not left:
            left = K
        for c in S:
            if c == '-':
                continue
            s.append(c.upper())
            left -= 1
            if left == 0:
                s.append('-')
                left = K
        if s and s[-1] == '-':
            s.pop()
        return ''.join(s)