首页 > 其他 > 详细

246. Strobogrammatic Number

时间:2015-12-01 01:41:49      阅读:264      评论:0      收藏:0      [点我收藏+]

题目:

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.

链接: http://leetcode.com/problems/strobogrammatic-number/

题解:

验证一个数是否是strobogrammatic number。我们可以用验证Palindrome的方法,从头部和尾部向中间遍历。这里因为这种数的条件比较少,所以我用了一个HashMap来保存所有合理的可能性。空间复杂度应该也可以算是O(1)的

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
    public boolean isStrobogrammatic(String num) {
        if(num == null || num.length() == 0)
            return false;
        int lo = 0, hi = num.length() - 1;
        Map<Character, Character> map = new HashMap<>();
        map.put(‘0‘, ‘0‘);
        map.put(‘1‘, ‘1‘);
        map.put(‘6‘, ‘9‘);
        map.put(‘8‘, ‘8‘);
        map.put(‘9‘, ‘6‘);
        
        while(lo <= hi) {
            char cLo = num.charAt(lo);
            if(!map.containsKey(cLo))
                return false;
            else if(map.get(cLo) != num.charAt(hi))
                return false;
            else {
                lo++;
                hi--;
            }
        }
        
        return true;
    }
}

 

Reference:

 

246. Strobogrammatic Number

原文:http://www.cnblogs.com/yrbbest/p/5008966.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!