-
Notifications
You must be signed in to change notification settings - Fork 177
/
411.py
77 lines (70 loc) · 2.57 KB
/
411.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
66
67
68
69
70
71
72
73
74
75
76
77
class Solution(object):
def extract_number(self, j, abbr, M):
num = 0
while j < M and abbr[j].isdigit():
num, j = num*10 + int(abbr[j]), j+1
return num, j
def valid(self, word, abbr):
i,j,N, M = 0,0,len(word), len(abbr)
while i < N and j < M:
if abbr[j].isalpha() and abbr[j] != word[i]:
return False
elif abbr[j].isalpha() and abbr[j] == word[i]:
i,j = i+1,j+1
elif abbr[j].isdigit():
if abbr[j] == '0':
return False
num, j = self.extract_number(j, abbr, M)
i = i+num
return (i==N and j == M)
def process_solution(self, so_far):
csofar, i, cnt = [], 0, 0
while i < len(so_far):
if so_far[i].isalpha():
csofar.append(so_far[i])
i, cnt = i+1, cnt+1
else:
num = 0
while i < len(so_far) and so_far[i].isdigit():
num, i = num+1, i+1
cnt = cnt + 1
csofar.append(str(num))
return "".join(csofar), cnt
def test(self, abbr, dictionary):
for wrd in dictionary:
if self.valid(wrd, abbr):
return False
return True
def helper(self, word, so_far, i, dictionary):
if i == len(word):
abbr, cnt = self.process_solution(so_far)
if cnt < self.result_len and self.test(abbr, dictionary):
self.result, self.result_len = abbr, cnt
return
else:
so_far.append("1")
self.helper(word, so_far, i+1, dictionary)
so_far.pop()
so_far.append(word[i])
self.helper(word, so_far, i+1, dictionary)
so_far.pop()
def minAbbreviation(self, target, dictionary):
"""
:type target: str
:type dictionary: List[str]
:rtype: str
"""
# Remove those words which can never be an abbreviation for target.
# This preprocessing will help us save time.
filtered_dictionary = []
for wrd in dictionary:
if len(wrd) != len(target):
continue
filtered_dictionary.append(wrd)
dictionary = filtered_dictionary
if len(dictionary) == 0:
return str(len(target))
self.result_len = len(target)+1
self.result, so_far, i = target, [], 0
self.helper(target, so_far, i, dictionary)
return self.result