LeetCode 246. 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.

Example 1:

Input:  "69"
Output: true

Example 2:

Input:  "88"
Output: true

Example 3:

Input:  "962"
Output: false

题解:

把几种对应关系加到HashMap中,两个指针向中间夹逼.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 class Solution {
 2     public boolean isStrobogrammatic(String num) {
 3         if(num == null || num.length() == 0){
 4             return true;
 5         }
 6         
 7         HashMap<Character, Character> hm = new HashMap<>();
 8         String cans = "0011886996";
 9         for(int i = 0; i<cans.length(); i+=2){
10             hm.put(cans.charAt(i), cans.charAt(i+1));
11         }
12         
13         int l = 0;
14         int r = num.length() - 1;
15         while(l <= r){
16             char left = num.charAt(l);
17             char right = num.charAt(r);
18             if(!hm.containsKey(left) || !hm.containsKey(right) || hm.get(left) != right || hm.get(right) != left){
19                 return false;
20             }
21             
22             l++;
23             r--;
24         }
25         
26         return true;
27     }
28 }

跟上Strobogrammatic Number IIStrobogrammatic Number III.

posted @ 2016-03-05 02:33  Dylan_Java_NYC  阅读(289)  评论(0编辑  收藏  举报