File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Premium Question
3+ """
4+ __author__ = 'Daniel'
5+
6+
7+ class Solution (object ):
8+ def minAbbreviation (self , target , dictionary ):
9+ """
10+ :type target: str
11+ :type dictionary: List[str]
12+ :rtype: str
13+ """
14+ ret = target
15+ for abbr in self .dfs (target ):
16+ if self .validate (dictionary , abbr ) and len (ret ) > len (abbr ):
17+ ret = abbr
18+
19+ return ret
20+
21+ def dfs (self , word ):
22+ """
23+ backtracking, pivoting letter
24+ :type word: str
25+ :rtype: List[str]
26+ """
27+ if not word :
28+ return ["" ]
29+
30+ ret = []
31+ for l in xrange (len (word )+ 1 ):
32+ left_num = str (l ) if l else ""
33+ for right in self .dfs (word [l + 1 :]):
34+ cur = left_num + word [l :l + 1 ]+ right
35+ ret .append (cur )
36+
37+ return ret
38+
39+ def validate (self , dictionary , abbr ):
40+ for w in dictionary :
41+ if self .validWordAbbreviation (w , abbr ):
42+ return False
43+
44+ return True
45+
46+ def validWordAbbreviation (self , word , abbr ):
47+ """
48+ pointers
49+ :type word: str
50+ :type abbr: str
51+ :rtype: bool
52+ """
53+ w = 0
54+ a = 0
55+ while w < len (word ) and a < len (abbr ):
56+ if abbr [a ].isdigit () and abbr [a ] != '0' :
57+ e = a
58+ while e < len (abbr ) and abbr [e ].isdigit (): e += 1
59+ num = int (abbr [a :e ])
60+ a = e
61+ w += num
62+ else :
63+ if word [w ] != abbr [a ]:
64+ return False
65+
66+ w += 1
67+ a += 1
68+
69+ return w == len (word ) and a == len (abbr )
70+
71+
72+ if __name__ == "__main__" :
73+ print Solution ().minAbbreviation ("apple" , ["blade" ])
You can’t perform that action at this time.
0 commit comments