Description
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Output: false
Solution
HashMap + Two-pointer, O(n), S(1)
class Solution {
public boolean isStrobogrammatic(String num) {
if (num == null || num.length() < 1) {
return false;
}
int[] from = {0, 1, 6, 8, 9};
int[] to = {0, 1, 9, 8, 6};
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < from.length; ++i) {
map.put(from[i], to[i]);
}
for (int i = 0, j = num.length() - 1; i <= j; ++i, --j) {
int val = num.charAt(i) - '0';
if (!map.containsKey(val)
|| map.get(val) != num.charAt(j) - '0') {
return false;
}
}
return true;
}
}