-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path482-license-key-formatting.py
65 lines (55 loc) · 1.93 KB
/
482-license-key-formatting.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'''
You are given a license key represented as a string S which consists only
alphanumeric character and dashes. The string is separated into N+1 groups by N
dashes.
Given a number K, we would want to reformat the strings 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 all lowercase letters should be
converted to uppercase.
Given a non-empty string S and a number K, format the string according to the
rules described above.
'''
#class Solution(object):
def licenseKeyFormatting(S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
n = len(S)
if n == 0 or n <= K:
return S.upper().replace("-", "")
# count number of alphanumeric characters
alnums = sum(i.isalnum() for i in S)
hyphens = S.count("-")
if alnums + hyphens < n:
print("String contains non-alphanumeric, non-hyphen characters")
return
# move values to new list
result = []
index = 0
alnumsPlaced = 0
groupLen = 0
firstGroup = alnums % K
if firstGroup > 0:
while groupLen < firstGroup: # create undersized first group if needed
if S[index].isalnum():
result.append(S[index].upper())
groupLen += 1
alnumsPlaced += 1
index += 1
result.append("-")
while alnumsPlaced < alnums: # create subsequent groups
groupLen = 0
while groupLen < K:
if S[index].isalnum():
result.append(S[index].upper())
alnumsPlaced += 1
groupLen += 1
index += 1
result.append("-")
result = result[:len(result) - 1] # remove trailing hyphen
result = ''.join(result)
return result
print(licenseKeyFormatting("a-a-a-a-", 1))