-
Notifications
You must be signed in to change notification settings - Fork 42
/
strobogrammatic-number.py
114 lines (96 loc) · 2.67 KB
/
strobogrammatic-number.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"""
246. Strobogrammatic Number
Easy
Given a string num which represents an integer, return true if num is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: num = "69"
Output: true
Example 2:
Input: num = "88"
Output: true
Example 3:
Input: num = "962"
Output: false
Constraints:
1 <= num.length <= 50
num consists of only digits.
num does not contain any leading zeros except for zero itself.
"""
# V0
class Solution(object):
def isStrobogrammatic(self, num):
d = {'0':'0','1':'1','6':'9','8':'8','9':'6'}
ans = ''
for n in num:
if n not in d:
return False
ans += d[n]
return ans[::-1] == num
# V1
# https://blog.csdn.net/danspace1/article/details/88944960
# ...: num = '69'
# ...: Solution().isStrobogrammatic(num)
# ...:
# Out[18]: True
# ...: num = '699'
# ...: Solution().isStrobogrammatic(num)
# ...:
# Out[19]: False
# ...: num = '6699'
# ...: Solution().isStrobogrammatic(num)
# ...:
# Out[20]: True
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
d = {'0':'0','1':'1','6':'9','8':'8','9':'6'}
ans = ''
for n in num:
if n not in d:
return False
ans += d[n]
return ans[::-1] == num
# V1'
# https://www.jiuzhang.com/solution/strobogrammatic-number/#tag-highlight-lang-python
class Solution:
"""
@param num: a string
@return: true if a number is strobogrammatic or false
"""
def isStrobogrammatic(self, num):
# write your code here
map = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
i, j = 0, len(num)-1
while i<=j:
if not num[i] in map or map[num[i]] != num[j]:
return False
i, j = i+1, j-1
return True
# V2
# need to double check
class Solution:
def isStrobogrammatic(self, nums):
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
for i, num in enumerate(list(nums)):
#print (num)
if str(num) in lookup:
pass
else:
return False
return True
# V3
class Solution:
# @param {string} num
# @return {boolean}
def isStrobogrammatic(self, num):
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
n = len(num)
for i in range((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