246. Strobogrammatic Number
https://www.lintcode.com/problem/strobogrammatic-number/description
https://leetcode.com/problems/strobogrammatic-number
247-strobogrammatic-number-ii
---
https://leetcode.com/problems/strobogrammatic-number
A mirror number is a number that looks the same when rotated 180 degrees (looked at upside down).For example, the numbers "69", "88", and "818" are all mirror numbers.
Write a function to determine if a number is mirror. The number is represented as a string.
---
Related problems247-strobogrammatic-number-ii
---
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
/** | |
* @param num: a string | |
* @return: true if a number is strobogrammatic or false | |
*/ | |
public boolean isStrobogrammatic(String num) { | |
Map<Character, Character> reverse = new HashMap<Character, Character>(); | |
reverse.put('6', '9'); | |
reverse.put('9', '6'); | |
reverse.put('0', '0'); | |
reverse.put('1', '1'); | |
reverse.put('8', '8'); | |
Set<Character> invalid = new HashSet<Character>(); | |
invalid.add('2'); | |
invalid.add('3'); | |
invalid.add('4'); | |
invalid.add('5'); | |
invalid.add('7'); | |
int i = 0, j = num.length() - 1; | |
while (i <= j) { | |
char first = num.charAt(i); | |
char second = num.charAt(j); | |
if (invalid.contains(first) || invalid.contains(second)) { | |
return false; | |
} | |
if (reverse.containsKey(first) && reverse.get(first) != second) { | |
return false; | |
} | |
i++; | |
j--; | |
} | |
return true; | |
} | |
} |