개발공부/algorithm

[Leetcode][python] 482: License key formatting - String

so.py 2021. 5. 1. 14:42

  • Leetcode 482: License key formatting
  • Level: Easy
  • Link
 

License Key Formatting - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

My Approach

A simple string slicing problem

class Solution:
    def licenseKeyFormatting(self, s: str, k: int) -> str:
        s = s.replace('-', '').upper()
        L = len(s)
        
        if L == 1:
            return s
        
        ans = ""
        ans += (s[0: L % k])
        
        for i in range(L % k, L, k):
            if len(ans) > 0:
                ans += '-'
            ans += s[i: i + k]
            
        return (ans)