题目地址:
https://leetcode.com/problems/strobogrammatic-number/
判断一个数字旋转 180 ° 180\degree 180°后是否还等于自己。我们认为 0 0 0旋转后变为 0 0 0, 1 1 1旋转后变为 1 1 1, 6 6 6旋转后变为 9 9 9, 8 8 8旋转后变为 8 8 8, 9 9 9旋转后变为 6 6 6。
思路是双指针。需要注意当两个指针相撞的时候还需要判断正中间的数是否是 0 , 1 , 8 0,1,8 0,1,8。代码如下:
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Solution {
public boolean isStrobogrammatic(String num) {
Map<Character, Character> map = new HashMap<>();
map.put('0', '0');
map.put('1', '1');
map.put('6', '9');
map.put('8', '8');
map.put('9', '6');
for (int i = 0, j = num.length() - 1; i <= j; i++, j--) {
char left = num.charAt(i), right = num.charAt(j);
if (i != j && !Objects.equals(map.get(left), right)) {
return false;
}
if (i == j) {
return map.containsKey(left) && map.get(left) == left;
}
}
return true;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。