题目:
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.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
链接: http://leetcode.com/problems/strobogrammatic-number/
题解:
验证一个数是否是strobogrammatic number。我们可以用验证Palindrome的方法,从头部和尾部向中间遍历。这里因为这种数的条件比较少,所以我用了一个HashMap来保存所有合理的可能性。空间复杂度应该也可以算是O(1)的
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution { public boolean isStrobogrammatic(String num) { if(num == null || num.length() == 0) return false; int lo = 0, hi = num.length() - 1; 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‘); while(lo <= hi) { char cLo = num.charAt(lo); if(!map.containsKey(cLo)) return false; else if(map.get(cLo) != num.charAt(hi)) return false; else { lo++; hi--; } } return true; } }
Reference:
原文:http://www.cnblogs.com/yrbbest/p/5008966.html