美文网首页
246. Strobogrammatic Number

246. Strobogrammatic Number

作者: Nancyberry | 来源:发表于2018-05-26 01:15 被阅读0次

Description

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

Solution

HashMap + Two-pointer, O(n), S(1)

class Solution {
    public boolean isStrobogrammatic(String num) {
        if (num == null || num.length() < 1) {
            return false;
        }
        
        int[] from = {0, 1, 6, 8, 9};
        int[] to = {0, 1, 9, 8, 6};
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < from.length; ++i) {
            map.put(from[i], to[i]);
        }
        
        for (int i = 0, j = num.length() - 1; i <= j; ++i, --j) {
            int val = num.charAt(i) - '0';
            
            if (!map.containsKey(val) 
                || map.get(val) != num.charAt(j) - '0') {
                return false;
            }
        }
        
        return true;
    }
}

相关文章

网友评论

      本文标题:246. Strobogrammatic Number

      本文链接:https://www.haomeiwen.com/subject/aqspjftx.html