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.
立即想到双指针,一个从左到右,一个从右到左,接下来想到哪些数满足 looks the same when rotated 180 degrees, 那就是0,1,8,(6,9),(9,6)。
我第一种方法没用Map, 纯粹比较,慢一些;第二种方法将满足要求的值存到map里。每次检查一下即可,速度会快很多。
推荐使用方法二!使用HashMap
Java code:
方法一:
public boolean isStrobogrammatic(String num) { if(num.length() == 0) { return true; } int len = num.length(); int i = 0, j = len-1; boolean flag = false; while(i <= j) { char x = num.charAt(i); char y = num.charAt(j); if((x == ‘1‘ && y == ‘1‘) || (x == ‘8‘ && y == ‘8‘) || (x == ‘0‘ && y == ‘0‘) || (x == ‘6‘ && y == ‘9‘) || (x == ‘9‘ && y == ‘6‘)){ flag = true; }else { flag = false; break; } i++; j--; } return flag; }
方法二: HashMap
public boolean isStrobogrammatic(String num) { Map<Character, Character> map = new HashMap<Character, Character>(); map.put(‘1‘, ‘1‘); map.put(‘0‘, ‘0‘); map.put(‘8‘, ‘8‘); map.put(‘6‘, ‘9‘); map.put(‘9‘, ‘6‘); int l = 0, r = num.length()-1; while(l <= r) { if(!map.containsKey(num.charAt(l))) { return false; } if(map.get(num.charAt(l)) != num.charAt(r)){ return false; } l++; r--; } return true; }
Reference:
1. https://leetcode.com/discuss/52273/accepted-java-solution
Leetcode Strobogrammatic Number
原文:http://www.cnblogs.com/anne-vista/p/4856653.html