246. Strobogrammatic Number
Probelm:
列举出可以rotate的数对,然后用同向双指针检查是否匹配。
Solution:
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: falseAnalysis:
列举出可以rotate的数对,然后用同向双指针检查是否匹配。
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public boolean isStrobogrammatic(String num) { Map<Character, Character> map = new HashMap<Character, Character>(); map.put('6', '9'); map.put('9', '6'); map.put('0', '0'); map.put('1', '1'); map.put('8', '8'); int l = 0, r = num.length() - 1; while (l <= r) { char c = num.charAt(l); if (!map.containsKey(c)) return false; if (num.charAt(r) != map.get(c)) return false; l++; r--; } return true; } } |
评论
发表评论