[LeetCode] 246. Strobogrammatic Number 对称数
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.
翻转180度后对称的数有:8->8, 0->0, 1->1, 6->9, 9->6,从两边向中间检查对应位置的两个数是否满足对称数就行了。比如619,先判断6和9是有映射的,然后1和自己又是映射,所以是对称数。有点像判断回文Palindrome,回文判断是否相等,这里判断是否满足那几个数字的条件。判断是可以直接写条件判断,也可以用HashMap存放数字的映射,然后用双指针从两边向中间查看。
Java:
public class Solution { public boolean isStrobogrammatic(String num) { HashMap<Character, Character> map = new HashMap<Character, Character>(); map.put('1','1'); map.put('0','0'); map.put('6','9'); map.put('9','6'); map.put('8','8'); int left = 0, right = num.length() - 1; while(left <= right){ if(!map.containsKey(num.charAt(right)) || num.charAt(left) != map.get(num.charAt(right))){ return false; } left++; right--; } return true; } }
Python:
class Solution: lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} def isStrobogrammatic(self, num): n = len(num) for i in xrange((n+1) / 2): if num[n-1-i] not in self.lookup or \ num[i] != self.lookup[num[n-1-i]]: return False return True
Python: wo
class Solution(): def strobogrammatic(self, s): lookup = {'1': '1', '8': '8', '0': '0', '6': '9', '9': '6'} i, j = 0, len(s) - 1 while i <= j: if s[i] not in lookup or lookup[s[i]] != s[j]: return False i += 1 j -= 1 return True
C++:
class Solution { public: bool isStrobogrammatic(string num) { unordered_map<char, char> m {{'0', '0'}, {'1', '1'}, {'8', '8'}, {'6', '9'}, {'9', '6'}}; for (int i = 0; i <= num.size() / 2; ++i) { if (m[num[i]] != num[num.size() - i - 1]) return false; } return true; } };
类似题目:
[LeetCode] 247. Strobogrammatic Number II 对称数II
[LeetCode] 248. Strobogrammatic Number III 对称数III
All LeetCode Questions List 题目汇总