Python3 Solution


  • 0
    J
    class Solution:
        def licenseKeyFormatting(self, S, K):
            """
            :type S: str
            :type K: int
            :rtype: str
            """
            # Remove dashes from input string
            noDash = S.replace("-", "")
            # Uppercase all alphabetic characters 
            allUpper = noDash.upper()
            # Since the first chunk of the formatted string is
            # where we want a chunk shorter than K characters, 
            # we reverse the string before the next step
            reved = allUpper[::-1]
            # This is the meat of the solution:
            # We create the list of K-length chunks using list comprehension.
            # Looping i from 0 to the length of the string (with dashes removed) by steps of K,
            # Take the subset of the string from index i to index i+K.
            # If the string is not divisible by K, 
            # the last index of chunkList contains the short group.
            chunkList = [reved[i:i+K] for i in range(0,len(reved), K)]
            # Finally, since the string was reversed before splitting, 
            # each chunk will be reversed.
            # So we build our final list of K-length groups by iterating backwards over
            # the previous list, and reversing each individual chunk.
            finalL = [x[::-1] for x in chunkList[::-1]]
            # Now we just return the elements our final list joined by a dashes! 
            return "-".join(finalL)
            
    

Log in to reply
 

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