38
38
39
39
<!-- 这里可写通用的实现逻辑 -->
40
40
41
+ ** 方法一:双指针模拟**
42
+
43
+ 我们定义一个数组 $d$,其中 $d[ i] $ 表示数字 $i$ 旋转 180° 之后的数字。如果 $d[ i] $ 为 $-1$,表示数字 $i$ 不能旋转 180° 得到一个数字。
44
+
45
+ 定义两个指针 $i$ 和 $j$,分别指向字符串的左右两端,然后不断向中间移动指针,判断 $d[ num[ i]] $ 和 $num[ j] $ 是否相等,如果不相等,说明该字符串不是中心对称数,直接返回 $false$ 即可。如果 $i \gt j$,说明遍历完了字符串,返回 $true$。
46
+
47
+ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串的长度。
48
+
41
49
<!-- tabs:start -->
42
50
43
51
### ** Python3**
47
55
``` python
48
56
class Solution :
49
57
def isStrobogrammatic (self , num : str ) -> bool :
50
- def match (a , b ):
51
- if a in {' 0' , ' 1' , ' 8' }:
52
- return a == b
53
- if a == ' 6' :
54
- return b == ' 9'
55
- if a == ' 9' :
56
- return b == ' 6'
57
- return False
58
-
59
- n = len (num)
60
- i, j = 0 , n - 1
58
+ d = [0 , 1 , - 1 , - 1 , - 1 , - 1 , 9 , - 1 , 8 , 6 ]
59
+ i, j = 0 , len (num) - 1
61
60
while i <= j:
62
- if not match(num[i], num[j]):
61
+ a, b = int (num[i]), int (num[j])
62
+ if d[a] != b:
63
63
return False
64
- i += 1
65
- j -= 1
64
+ i, j = i + 1 , j - 1
66
65
return True
67
66
```
68
67
@@ -73,27 +72,48 @@ class Solution:
73
72
``` java
74
73
class Solution {
75
74
public boolean isStrobogrammatic (String num ) {
76
- int n = num. length();
77
- for (int i = 0 , j = n - 1 ; i <= j; ++ i, -- j) {
78
- if (! match(num. charAt(i), num. charAt(j))) return false ;
75
+ int [] d = new int [] {0 , 1 , - 1 , - 1 , - 1 , - 1 , 9 , - 1 , 8 , 6 };
76
+ for (int i = 0 , j = num. length() - 1 ; i <= j; ++ i, -- j) {
77
+ int a = num. charAt(i) - ' 0' , b = num. charAt(j) - ' 0' ;
78
+ if (d[a] != b) {
79
+ return false ;
80
+ }
79
81
}
80
82
return true ;
81
83
}
84
+ }
85
+ ```
82
86
83
- private boolean match ( char a , char b ) {
84
- switch (a) {
85
- case ' 0 ' :
86
- case ' 1 ' :
87
- case ' 8 ' :
88
- return a == b;
89
- case ' 6 ' :
90
- return b == ' 9 ' ;
91
- case ' 9 ' :
92
- return b == ' 6 ' ;
93
- default :
94
- return false ;
87
+ ### ** C++ **
88
+
89
+ ``` cpp
90
+ class Solution {
91
+ public :
92
+ bool isStrobogrammatic(string num) {
93
+ vector< int > d = {0, 1, -1, -1, -1, -1, 9, -1, 8, 6};
94
+ for (int i = 0, j = num.size() - 1; i <= j; ++i, --j) {
95
+ int a = num [ i ] - '0', b = num [ j ] - '0';
96
+ if (d [ a ] != b) {
97
+ return false;
98
+ }
95
99
}
100
+ return true;
96
101
}
102
+ };
103
+ ```
104
+
105
+ ### **Go**
106
+
107
+ ```go
108
+ func isStrobogrammatic(num string) bool {
109
+ d := []int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6}
110
+ for i, j := 0, len(num)-1; i <= j; i, j = i+1, j-1 {
111
+ a, b := int(num[i]-'0'), int(num[j]-'0')
112
+ if d[a] != b {
113
+ return false
114
+ }
115
+ }
116
+ return true
97
117
}
98
118
```
99
119
0 commit comments