forked from nyuhuyang/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strobogrammatic-number-iii.py
74 lines (64 loc) · 2.56 KB
/
strobogrammatic-number-iii.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
# Time: O(5^(n/2))
# Space: O(n)
class Solution:
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
cache = {}
# @param {string} low
# @param {string} high
# @return {integer}
def strobogrammaticInRange(self, low, high):
count = self.countStrobogrammaticUntil(high, False) - \
self.countStrobogrammaticUntil(low, False) + \
self.isStrobogrammatic(low)
return count if count >= 0 else 0
def countStrobogrammaticUntil(self, num, can_start_with_0):
if can_start_with_0 and num in self.cache:
return self.cache[num]
count = 0
if len(num) == 1:
for c in ['0', '1', '8']:
if num[0] >= c:
count += 1
self.cache[num] = count
return count
for key, val in self.lookup.iteritems():
if can_start_with_0 or key != '0':
if num[0] > key:
if len(num) == 2: # num is like "21"
count += 1
else: # num is like "201"
count += self.countStrobogrammaticUntil('9' * (len(num) - 2), True)
elif num[0] == key:
if len(num) == 2: # num is like 12".
if num[-1] >= val:
count += 1
else:
if num[-1] >= val: # num is like "102".
count += self.countStrobogrammaticUntil(self.getMid(num), True);
elif (self.getMid(num) != '0' * (len(num) - 2)): # num is like "110".
count += self.countStrobogrammaticUntil(self.getMid(num), True) - \
self.isStrobogrammatic(self.getMid(num))
if not can_start_with_0: # Sum up each length.
for i in xrange(len(num) - 1, 0, -1):
count += self.countStrobogrammaticByLength(i)
else:
self.cache[num] = count
return count
def getMid(self, num):
return num[1:len(num) - 1]
def countStrobogrammaticByLength(self, n):
if n == 1:
return 3
elif n == 2:
return 4
elif n == 3:
return 4 * 3
else:
return 5 * self.countStrobogrammaticByLength(n - 2)
def isStrobogrammatic(self, num):
n = len(num)
for i in xrange((n+1) / 2):
if num[n-1-i] not in self.lookup or \
num[i] != self.lookup[num[n-1-i]]:
return False
return True