leetcode 065 —— Valid Number

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.


思路:综合考虑不同的情况,代码写得很丑,也花了很长时间,但此题真正牛逼的解法是状态机,看这里

class Solution {
public:
	bool isNumber(string s) {
		int n = s.size();
		int start = 0;
		int end = n - 1;
		while (start < end&&(s[start]==' '||s[end]==' ')){   //去除左右的空格
			if (s[start] == ' '&&start < end)
				start++;
			if (s[end] == ' '&&start < end)
				end--;
		}
		cout << start << ' ' << end << endl;
		int cnt1 = 0;	//cnt1记录点的个数
		int pos1 = -1;
		int cnt2 = 0;	//cnt2记录e的个数
		int pos2 = -1;
		int cnt3 = 0;   //记录数字的数量
		for (int i = start; i <= end; i++){
			if (isdigit(s[i]))
				cnt3++;
			else if (s[i] == '.'){
				cnt1++;
				pos1 = i;                   //记录点出现的位置
				if (cnt1>1)				
					return false;
				if (pos2>0&&pos2<pos1)      //  e . 的情况
					return false;
				if ((i == start&&s[i + 1] == 'e') || (i == end&&s[i - 1] == 'e'))
					return false;
			}
			else if (s[i] == 'e'){
				cnt2++;
				pos2 = i;
				if (cnt2 > 1)
					return false;
				if (i == start || i == end)
					return false;
			    if (!isdigit(s[i - 1])&& s[i - 1] != '.')
					return false;
			}
			else if (s[i] == '+' || s[i] == '-'){
				if (i == end)
					return false;
				if (i != start){
					if (s[i - 1] != 'e' || !isdigit(s[i + 1]))
						return false;
				}
			}
			else
				return false;
		}
		if (cnt3 == 0)  //数字的数量为0
			return false;
		return true;
	}
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值