leetcode No65. Valid Number

来源:互联网 发布:c语言大小写转化 编辑:程序博客网 时间:2024/05/22 00:35

Question:

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.

判断字符串是否是有效的数字表示

Algorithm:

用有效状态机解,这篇博客有详细的解释http://noalgo.info/995.html

Accepted Code:

class Solution {public:    bool isNumber(string s) {        int tran[][6]=        {            -1, 0, 1, 2,-1, 3,            -1,-1,-1, 2,-1, 3,            -1,-1,-1,-1,-1, 4,            -1, 5,-1, 4, 6, 3,            -1, 5,-1,-1, 6, 4,            -1, 5,-1,-1,-1,-1,            -1,-1, 7,-1,-1, 8,            -1, 5,-1,-1,-1, 8,            -1, 5,-1,-1,-1, 8,        };         int state=0;        for(int i=0;i<s.size();i++)        {            int input=0;            if(s[i]==' ')                input=1;            else if(s[i]=='+' || s[i]=='-')                input=2;            else if(s[i]=='.')                input=3;            else if(s[i]=='e')                input=4;            else if(s[i]>='0' && s[i]<='9')                input=5;            else                return false;            state=tran[state][input];            if(state==-1)                return false;        }        return state==3 || state==4 || state==5 || state==8;    }};



0 0
原创粉丝点击