246. Strobogrammatic Number - Easy
阿新 • • 發佈:2018-12-24
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
把符合條件的數字(0,1,6,8,9)放進HashMap,雙指標分別從0, length-1位置向中間掃描字串
time: O(n), space: O(1)
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'); int i = 0, j = num.length() - 1; while(i <= j) { char s = num.charAt(i), t = num.charAt(j); if(s != t && !map.containsKey(s) || !map.containsKey(t) || map.get(s) != t) return false; i++; j--; } return true; } }