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.
只要知道什么是strobogrammatic数, 这道题并不难。翻转180度对称的数字就那么几个:0->0, 1->1, 6->9, 8->8, 9->6,然后从两边向中间逐个比较对应位置的数字是否有映射关系。如果这个数包含有奇数个数字,中间那个只能是 0、1、8,不能是6和9。非常straightforward的C++ 实现如下。
class Solution {
public:
bool isStrobogrammatic(string nums){
int start = 0, end = nums.length() - 1;
while (start != end)
{
if ((nums[start] == 1 && nums[end] == 1) ||
(nums[start] == 8 && nums[end] == 8) ||
(nums[start] ==6 && nums[end] == 9) ||
(nums[start] == 9 && nums[end] == 6) )
{
++start;
--end;
} else {
return false;
}
}
if (start == end)
{
if ((nums[start] == '0') || (nums[start] == '1') || (nums[start] == '8'))
return true;
else
return false;
}
}
};
比上面代码更简洁的方法是建立一个查询表, 代码如下。
class Solution {
public:
bool isStrobogrammatic(string nums) {
unordered_map<char, char> mapping;
mapping['0'] = '0';
mapping['1'] = '1';
mapping['6'] = '9';
mapping['8'] = '8';
mapping['9'] = '6';
int start = 0, end = nums.length() - 1;
while (start <= end)
{
if ((mapping.find(nums[start]) == mapping.end()) ||
(mapping.find(nums[end]) == mapping.end()) ||
(mapping[nums[start]] != nums[end]))
return false;
++start;
--end;
}
return true;
}
};