one-liner


  • 1
    def license_key_formatting(s, k)
      s.upcase.tr('-', '').reverse.scan(/.{1,#{k}}/).join('-').reverse
    end
    

  • 0
    Z

    any solution for one line python ? I can only do it in two lines.

    class Solution(object):
        def licenseKeyFormatting(self, S, K):
            """
            :type S: str
            :type K: int
            :rtype: str
            """
            s = S.replace('-', '').upper()[::-1]
            return '-'.join([s[i:i+K] for i in xrange(0, len(s), K)])[::-1]
    

    <50ms, beats 89%


  • 0

    @zqfan You can do the equivalent of my Ruby one-liner in Python, using a regular expression. I actually wrote it in Python first, but then switched to Ruby and showed that instead because it's shorter and more importantly because it reads nicely step by step from left to right.


Log in to reply
 

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