码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Strobogrammatic Number

时间:2016-03-05 06:49:04      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里: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

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5244016.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!