leetcode with python:482. License Key Formatting

题目:

You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.

We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.

Return the reformatted license key.

给定一个由数字,字母和"-"构成的字串s和一数k
将s的非"-"元素分为k个一组由"-"间隔回传,字母全数改为大写
第一组元素个数可小于k,因应非"-"元素个数可能不能被k整除
ex:input:"2-5g-3-J",2=>output:"2-5G-3J"

这题的範畴为字串的操作

class Solution:    def licenseKeyFormatting(self, s: str, k: int) -> str:        s=s.replace("-","")                ans=[]        l=len(s)        x=l%k        y=l//k        if x:            ans.append(s[:x])                for i in range(y):            ans.append(s[x+i*k:x+(i+1)*k])                    return "-".join(ans).upper()

先将s中的"-"去除,接着开始分组
取字串长度除k的余数(x),决定第一组的元素个数
若余数不为0,将s前x个字元构成的字串存入ans
之后每k个构成一个字串存入ans

最后用join将ans的各字串以"-"相连
再用upper()将字母全改为大写
最后执行时间47ms(faster than 91.76%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章