确定有限状态自动机
var isNumber = function(s) {
const states = [
{ space: 0, sign: 1, digit: 2, dot: 4 },
{ digit: 2, dot: 4 },
{ digit: 2, dot: 3, e: 5, space: 8},
{ digit: 3, e: 5, space: 8 },
{ digit: 3 },
{ sign: 6, digit: 7 },
{ digit: 7 },
{ digit: 7, space: 8 },
{ space: 8 }
];
let index = 0;
for (let i=0; i<s.length; i++) {
let cur = s.charAt(i);
if ((/\d/.test(cur))) {
t = 'digit'
} else if (['+', '-'].includes(cur)) {
t = 'sign'
} else if (['e', 'E'].includes(cur)) {
t = 'e'
} else if ('.' == cur) {
t = 'dot'
} else if (' ' == cur) {
t = 'space'
} else {
t = 'unknown'
}
if (!states[index].hasOwnProperty(t)) return false;
index = states[index][t]
}
return [2,3,7,8].includes(index);
};
数学问题