Strobogrammatic Number -- Leetcode 246

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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值