LeetCode Strobogrammatic Number
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Strobogrammatic Number相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/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.
题解:
把几种对应关系加到HashMap中,两个指针向中间夹逼.
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public boolean isStrobogrammatic(String num) { 3 HashMap<Character, Character> hm = new HashMap<Character, Character>(); 4 hm.put(‘6‘,‘9‘); 5 hm.put(‘9‘,‘6‘); 6 hm.put(‘1‘,‘1‘); 7 hm.put(‘0‘,‘0‘); 8 hm.put(‘8‘,‘8‘); 9 10 int l = 0; 11 int r = num.length() - 1; 12 while(l <= r){ 13 if(!hm.containsKey(num.charAt(l))){ 14 return false; 15 }else if(hm.get(num.charAt(l)) != num.charAt(r)){ 16 return false; 17 }else{ 18 l++; 19 r--; 20 } 21 } 22 return true; 23 } 24 }
以上是关于LeetCode Strobogrammatic Number的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Strobogrammatic Number 对称数
Leetcode 246: Strobogrammatic Number
[LeetCode] Strobogrammatic Number III 对称数之三
[LeetCode] Strobogrammatic Number III