[LeetCode] 246. Strobogrammatic Number 对称数
LeetCode number 对称
2023-09-27 14:28:37 时间
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 题目汇总
相关文章
- 别迷茫了,师兄告诉你怎么刷 LeetCode
- Leetcode: Nested List Weight Sum
- Leetcode: Number of 1 Bits
- Leetcode: Valid Number
- Leetcode: Longest Common Prefix
- Leetcode刷题记录:计算复数乘法
- [LeetCode] Minimum Path Sum
- 【LeetCode】263. Ugly Number
- 【LeetCode】200. Number of Islands (2 solutions)
- 【LeetCode】191. Number of 1 Bits
- [LeetCode] 1342. Number of Steps to Reduce a Number to Zero 将数字变成 0 的操作次数
- [LeetCode] 1301. Number of Paths with Max Score 最大得分的路径数目
- [LeetCode] 1189. Maximum Number of Balloons 气球的最大数量
- [LeetCode] 1056. Confusing Number 混淆的数字
- [LeetCode] 1178. Number of Valid Words for Each Puzzle 猜字谜
- [LeetCode] 1020. Number of Enclaves 飞地的数量
- [LeetCode] 829. Consecutive Numbers Sum 连续数字之和
- [LeetCode] Valid Parenthesis String 验证括号字符串
- [LeetCode] Number of Boomerangs 回旋镖的数量
- [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)