zoukankan      html  css  js  c++  java
  • 【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)
  • 相关阅读:
    自定义函数
    内置函数
    炸裂函数explode
    -bash:ls:command not found,执行命令总是报找不到
    函数
    C#的lock用法
    获取客户端Ip地址方法
    Grunt基础
    常用Sql
    HandleBars
  • 原文地址:https://www.cnblogs.com/seyjs/p/9724948.html
Copyright © 2011-2022 走看看