[Leetcode] 246. Strobogrammatic Number 解题报告

来源:互联网 发布:小米网络收音机改软件 编辑:程序博客网 时间:2024/05/16 14:27

题目

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.

思路

注意到0-9中有五个数字满足这种“镜像对称”,所以我们将它们放在一个哈希表中,然后遍历num中的前一半字符(包括最中间的字符),一旦发现某字符不在哈希表中,或者虽然是,但是在后面的对应位置上的字符不是它的“镜像对称”字符,就返回false。如果检查完所有的字符都没有问题,则返回true。

代码

class Solution {public:    bool isStrobogrammatic(string num) {        unordered_map<char, char> hash;        hash['0'] = '0';        hash['1'] = '1';        hash['8'] = '8';        hash['6'] = '9';        hash['9'] = '6';        int length = num.length();        for(int i = 0; i < (length + 1) / 2; ++i) {            if(hash.count(num[i]) == 0 || hash[num[i]] != num[length - 1 - i]) {                return false;            }        }        return true;    }};