Python solution


  • 7
    Y
    class Solution(object):
        def licenseKeyFormatting(self, S, K):
            """
            :type S: str
            :type K: int
            :rtype: str
            """
            S = S.upper().replace('-','')
            size = len(S)
            s1 = K if size%K==0 else size%K
            res = S[:s1]
            while s1<size:
                res += '-'+S[s1:s1+K]
                s1 += K
            return res
    

  • 0
    X

    possible small improvement: putting replace in front of upper


  • 0
    M

    Yours is definitely shorter than mine:

        def licenseKeyFormatting(self, S, K):
            """
            :type S: str
            :type K: int
            :rtype: str
            """
            count = 0
            q= collections.deque()
            S = S.replace('-','')
            for i in reversed(S): # returns an iterator
                if i.isalnum():
                    count += 1
                    q.appendleft(i.upper())
                    if count % K == 0 and count < len(S):
                        q.appendleft("-")            
            return ''.join(q)
    

  • 1
    S

    This will be very slow though. Since string is inmutable in Python. This is essentially creating a new string with every iteration and cause a n^2 performance


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.