题目:
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%)
那我们下题见