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)
  • 相关阅读:
    控制器的功能和工作原理
    数据通路的功能和基本结构
    指令的执行过程
    CPU的功能和基本组成结构
    CSS介绍
    html内容
    web简单介绍
    事务隔离机制介绍
    多版本并发控制MVCC
    数据库锁机制
  • 原文地址:https://www.cnblogs.com/seyjs/p/9724948.html
Copyright © 2011-2022 走看看