[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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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:
1 2 3 4 5 6 7 8 9 10 | 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
1 2 3 4 5 6 7 8 9 10 11 | 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++:
1 2 3 4 5 6 7 8 9 10 | 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 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?