{空格}{+/-}{整數或浮點數}{e}{+/-}{整數}{空格}
class Solution {
public:
enum State {
PRE_SPACE,
SIGN,
BEFORE_PT_NUM,
POINT,
AFTER_PT_NUM,
EXP,
AFTER_EXP_SIGN,
AFTER_EXP_NUM,
POST_SPACE
};
bool isNumber(string s) {
bool flag[9] = {false};
State state = PRE_SPACE;
for (std::string::iterator iter = s.begin() ; iter != s.end() ; iter ++) {
switch (state) {
case PRE_SPACE:
if (' ' == *iter) {
state = PRE_SPACE;
}
else if ('+' == *iter || '-' == *iter) {
state = SIGN;
if (flag[state]) {
return false;
}
}
else if ('0' <= *iter && '9' >= *iter) {
state = BEFORE_PT_NUM;
}
else if ('.' == *iter) {
state = POINT;
if (flag[state]) {
return false;
}
}
else {
return false;
}
flag[state] = true;
break;
case SIGN:
if ('0' <= *iter && '9' >= *iter) {
state = BEFORE_PT_NUM;
}
else if ('.' == *iter) {
state = POINT;
if (flag[state]) {
return false;
}
}
else {
return false;
}
flag[state] = true;
break;
case BEFORE_PT_NUM:
if ('0' <= *iter && '9' >= *iter) {
state = BEFORE_PT_NUM;
}
else if ('.' == *iter) {
state = POINT;
if (flag[state]) {
return false;
}
}
else if ('e' == *iter) {
state = EXP;
if (flag[state]) {
return false;
}
}
else if (' ' == *iter) {
state = POST_SPACE;
}
else {
return false;
}
break;
case POINT:
if ('0' <= *iter && '9' >= *iter) {
state = AFTER_PT_NUM;
}
else if ('e' == *iter) {
state = EXP;
if (flag[state]) {
return false;
}
}
else if (' ' == *iter) {
state = POST_SPACE;
}
else {
return false;
}
break;
case AFTER_PT_NUM:
if ('0' <= *iter && '9' >= *iter) {
state = AFTER_PT_NUM;
}
else if ('e' == *iter) {
state = EXP;
if (flag[state]) {
return false;
}
}
else if (' ' == *iter) {
state = POST_SPACE;
}
else {
return false;
}
break;
case EXP:
if ('+' == *iter || '-' == *iter) {
state = AFTER_EXP_SIGN;
if (flag[state]) {
return false;
}
}
else if ('0' <= *iter && '9' >= *iter) {
state = AFTER_EXP_NUM;
}
else {
return false;
}
break;
case AFTER_EXP_SIGN:
if ('0' <= *iter && '9' >= *iter) {
state = AFTER_EXP_NUM;
}
else {
return false;
}
break;
case AFTER_EXP_NUM:
if ('0' <= *iter && '9' >= *iter) {
state = AFTER_EXP_NUM;
}
else if (' ' == *iter) {
state = POST_SPACE;
}
else {
return false;
}
break;
case POST_SPACE:
if (' ' == *iter) {
state = POST_SPACE;
}
else {
return false;
}
break;
default:
return false;
}
flag[state] = true;
}
if ((BEFORE_PT_NUM == state || POINT == state || AFTER_PT_NUM == state || AFTER_EXP_NUM == state || POST_SPACE == state) &&
(flag[BEFORE_PT_NUM] || flag[AFTER_PT_NUM])) {
return true;
}
return false;
}
};
沒有留言:
張貼留言