题目如下:
解题思路:题目非常简单,没什么好说的。但是有一个地方我不明白,我最初解法是直接用字符串进行拼接的,但是会超时;改成用数组就好了,在本地测试,两种方法的执行时间相差只有几毫秒。
代码如下:
class Solution(object): #字符串解法,会超时 def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace('-', '').upper() remainder = len(S) % K res, inx = '', 0 if remainder != 0: res = S[:remainder] + '-' inx = remainder while inx < len(S): res += S[inx:inx + K] res += '-' inx += K return res[:-1] #数组解法,通过 def licenseKeyFormatting2(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace('-', '').upper() remainder = len(S) % K res, inx = [], 0 if remainder != 0: res.append(S[:remainder]) inx = remainder while inx < len(S): res.append(S[inx:inx + K]) inx += K return '-'.join(res)