forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlicense_number.py
More file actions
40 lines (31 loc) · 1.1 KB
/
license_number.py
File metadata and controls
40 lines (31 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
License Key Formatting
Given a license key string and a group size k, reformat the key so that each
group contains exactly k characters, separated by dashes.
Reference: https://leetcode.com/problems/license-key-formatting/
Complexity:
Time: O(n) where n is the length of the key
Space: O(n)
"""
from __future__ import annotations
def license_number(key: str, group_size: int) -> str:
"""Reformat a license key string into groups of a given size.
Args:
key: The license key string with dashes.
group_size: The desired size of each group.
Returns:
The reformatted license key with groups separated by dashes.
Examples:
>>> license_number("a-bc-dfd-df", 2)
'ab-cd-fd-df'
"""
result: list[str] = []
alphanumeric: list[str] = []
for char in key:
if char != "-":
alphanumeric.append(char)
for index, char in enumerate(reversed(alphanumeric)):
result.append(char)
if (index + 1) % group_size == 0 and index != len(alphanumeric) - 1:
result.append("-")
return "".join(result[::-1])