LeetCode 66. Valid Number

1. 前导后导空格去掉。若出现空格将字符串截成两段的情况,返回false. 将结果压入string对象中

2. 遍历string, 若出现非数字,非加减号,非小数点,非e的情况,返回false. 

3. 若出现e, 判断e前和e后的字串(str.substr(0, pos)和str.substr(pos+1))是否合法(注意到e后的字串不能有小数点)

4. 若没出现e, 判断str是否合法即可。


代码:

class Solution 
{
public:
    bool isNumber(const char *s) 
    {
        string str;
        size_t pos = string::npos;
        bool begin_space=true, number_finish=false;

        // 去掉前导后导空格
        for (int i = 0; i < strlen(s); ++ i)
        {
        	if (s[i] == ' ')
        	{
        		if (begin_space == true)
        		{
        			continue;
        		} else
        		{
        			number_finish = true;
        		}
        	} else if(number_finish == false) // s[i]!=' '
        	{
        		begin_space = false;
        		str.push_back(s[i]);
        	} else
        	{
        		return false;
        	}
        }
        // 判断是否有非法字符,同时寻找e,注意到第二次找到e将返回false
        for (size_t i = 0; i < str.size(); ++ i)
        {
        	if (str[i]=='e' && pos==string::npos)
        	{
        		pos = i;
        	} else if (str[i]!='-' && str[i]!='+' && str[i]!='.'
        		&& (str[i]<'0'||str[i]>'9'))
        	{
        		return false;
        	} 
        }

        if (pos==str.size()-1) // last character is 'e'
        {
        	return false;
        } else if (pos == string::npos) // no 'e'
        {
        	return gao(str, 1);
        } else
        {
        	return gao(str.substr(0, pos), 1) && gao(str.substr(pos+1), 0);
        }
    }
private:
	bool gao(const string& str, int dot_available)
	{
		int dot_cnt = 0;
		bool has_digit=false;
		for (int i = 0; i <str.size(); ++ i)
		{
			dot_cnt = str[i]=='.'? dot_cnt+1: dot_cnt;
			if (i!=0 && (str[i]=='+'||str[i]=='-'))
			{
				return false;
			} else if (str[i]>='0' && str[i]<='9')
			{
				has_digit = true;
			}
		}
		return dot_cnt<=dot_available && has_digit;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值