您的位置:首页 > 其它

[Leetcode] 246. Strobogrammatic Number 解题报告

2017-06-30 14:51 344 查看
题目

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: