靈感來源?
- 保持更新,努力學習
- python腳本學習
密鑰格式化
解題思路
- 移除原字符串中的所有破折號,并將小寫字母轉換為大寫。
- 從后向前遍歷處理后的字符串,每?
K
?個字符為一組。 - 最后將各組逆序拼接,并用破折號分隔。
class Solution:def licenseKeyFormatting(self, S: str, K: int) -> str:# 移除所有破折號并轉換為大寫clean = S.replace('-', '').upper()n = len(clean)if n == 0:return ''# 計算第一個分組的長度first_len = n % Kif first_len == 0:first_len = Kgroups = []# 添加第一個分組groups.append(clean[:first_len])# 從第一個分組后的位置開始,每K個字符為一組for i in range(first_len, n, K):groups.append(clean[i:i+K])# 用破折號連接所有分組return '-'.join(groups)
逐行解釋
class Solution:def licenseKeyFormatting(self, S: str, K: int) -> str:# 移除所有破折號并將小寫字母轉換為大寫# 例如:S="a-b-c-d" → clean="ABCD"clean = S.replace('-', '').upper()n = len(clean)# 處理空字符串的特殊情況if n == 0:return ''# 計算第一個分組的長度# 如果總長度能被K整除,第一個分組長度為K;否則為余數first_len = n % Kif first_len == 0:first_len = K# 存儲所有分組的列表groups = []# 添加第一個分組(可能比K短)groups.append(clean[:first_len])# 從第一個分組后的位置開始,每K個字符為一組# 例如:clean="ABCDEFG", K=3, first_len=1 → 分組為["A", "BCD", "EFG"]for i in range(first_len, n, K):groups.append(clean[i:i+K])# 用破折號連接所有分組并返回return '-'.join(groups)