• 【leetcode】482. License Key Formatting


    题目如下:

    解题思路:题目非常简单,没什么好说的。但是有一个地方我不明白,我最初解法是直接用字符串进行拼接的,但是会超时;改成用数组就好了,在本地测试,两种方法的执行时间相差只有几毫秒。

    代码如下:

    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)
  • 相关阅读:
    c# 获取iis地址
    c# 导入导出Excel
    ffmpeg 转成MP3采样率8000
    c# 百度api语音识别
    c# 文件转换成base64
    js截取文件的名称
    js checkbox获取选中的值
    js base64位和c# Base64位转换
    笨方法学Python——习题16
    Python学习问题
  • 原文地址:https://www.cnblogs.com/seyjs/p/9724948.html
Copyright © 2020-2023  润新知