246. Strobogrammatic Number

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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,087评论 0赞 10
  • 简一在新单位第一次参加集体活动是即将到来的三八节。全体女员工出游。 陌生的环境,新的同事,对于一个不会自来熟的人来...
    锦公子0925阅读 397评论 2赞 2
  • 梅雨季,俗称黄梅天 是每年6月中下旬至7月上半月之间 持续阴天有雨的气候现象 每年这个时候 中国长江中下游地区、上...
    yinlor阅读 855评论 0赞 0
  • ①工作观 干法这本书我听樊登老师讲过,而让我点开这本书的原因是我当时对本职工作开始厌烦,非常不喜欢做索然无味的工作...
    奔跑的丸子啊阅读 789评论 2赞 49

友情链接更多精彩内容