您的位置:首页 > 其它

LeetCode65 Valid Number

2015-08-16 19:29 381 查看

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.

thinking

通信软件课上学了FSM,看到这题的时候眼前一亮,但苦于不会敲C,幸好从/article/8001175.htmlhttps://github.com/fuwutu/LeetCode/blob/master/Valid%20Number.cpp上看到了相关解法。下图给出了部分状态转移例子(图太丑TNT)。



在交题的时候发现代码是有一点点bug的,导致测试案例有的没过,这是修改之后的版本(非原创)

bool isNumber(char* s) {
enum InputType
{
INVALID,    // 0
SPACE,      // 1
SIGN,       // 2
DIGIT,      // 3
DOT,        // 4
EXPONENT,   // 5
NUM_INPUTS  // 6
}inputType;
inputType= INVALID;

int transitionTable[][NUM_INPUTS] =
{
-1,  0,  3,  1,  2, -1,     // next states for state 0
-1,  8, -1,  1,  4,  5,     // next states for state 1
-1, -1, -1,  4, -1, -1,     // next states for state 2
-1, -1, -1,  1,  2, -1,     // next states for state 3
-1,  8, -1,  4, -1,  5,     // next states for state 4
-1, -1,  6,  7, -1, -1,     // next states for state 5
-1, -1, -1,  7, -1, -1,     // next states for state 6
-1,  8, -1,  7, -1, -1,     // next states for state 7
-1,  8, -1, -1, -1, -1,     // next states for state 8
};

int state = 0;
while (*s != '\0')
{

if (isspace(*s))
inputType = SPACE;
else if (*s == '+' || *s == '-')
inputType = SIGN;
else if (isdigit(*s))
inputType = DIGIT;
else if (*s == '.')
inputType = DOT;
else if (*s == 'e' || *s == 'E')
inputType = EXPONENT;
else inputType=INVALID; //修改
state = transitionTable[state][inputType];

if (state == -1)
return false;
else
++s;
}

return state == 1 || state == 4 || state == 7 || state == 8;

}


小结:enum的用法,transition[ ][NUM_INPUTS]数组的定义,以及最终状态的判断。

此思路值得借鉴。

try:
float(s.strip())
return True
except:
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: