美文网首页
65. Valid Number

65. Valid Number

作者: Al73r | 来源:发表于2017-10-16 13:38 被阅读0次

题目

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.

分析

这种故意把题目写得模糊的题目,一般都会被选手们标记为dislike。我也不是很喜欢这种题。不过这题感觉并不难,就是有点烦而已。判断的条件罗列如下:

  • 开头和结尾可以是空格,其余位置不允许出现空格
  • 空格除外的部分,开头可以有一个正负号
  • 剩下的部分,只能是数字、'e'、正负号或者小数点,且除数字外,都只能出现一次
  • 这部分中,只能以小数点和数字开头
  • 正负号只能出现在'e'的后面
  • e的后面必须接整数,可以带正负号
  • e的前面必须有数字,可以是整数或这小数,小数可以省略小数点前或者后面的零(但不能都省略)

实现

class Solution {
public:
    bool isNumber(string s) {
        bool exp=false, point=false, num=false;
        int i=0, start, end, epos, ppos;
        while(i<s.size() && s[i]==' ') i++;
        if(s[i]=='-' || s[i]=='+') i++;
        start = i;
        while(i<s.size() && s[i]!=' '){
            if(s[i]=='e'){
                if(exp) return false;
                exp = true;
                epos = i;
                if(i+1<s.size() && (s[i+1]=='-' || s[i+1]=='+')) i++;
            }
            else if(s[i]=='.'){
                if(point||exp) return false;
                point =true;
                ppos = i;
            }
            else if(s[i]<'0' || s[i]>'9')
                return false;
            else{
                num = true;
            }
            i++;
        }
        end = i-1;
        if(exp && (
            (start == epos || end == epos) || (epos+1<s.size() && (s[epos+1]=='-' || s[epos+1]=='+') && (epos+1==end))
        )) return false;
        if(!num || (exp && point && ppos==start && ppos==epos-1)) return false;
        while(i<s.size() && s[i]==' ') i++;
        return i==s.size();
    }
};

思考

这题我是边改边提交边看数据来做的,这样的做法不值得推荐。希望以后能够一次通过吧。

相关文章

网友评论

      本文标题:65. Valid Number

      本文链接:https://www.haomeiwen.com/subject/liskuxtx.html