題目:
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%)
那我們下題見