从慕课网课程中截来的图
解题步骤:
①构建一个表示状态的图;
②遍历字符串,并沿着图走,如果到了某个节点无路可走就返回false;
③遍历结束,如果走到了3/5/6就返回true,否则返回false
其实整体思路不难,但是代码是抄来的,关键就是要能够画出来状态图
for(c of s)其实就可以遍历s中的每一个元素,但是加上s.trim()的时候,就可以将前后的空格去除,减小资源占用率
/**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
const graph = {
0 : {'blank':0,'sign':1,'.':2,'digit':6},
1 : {'digit':6,'.':2},
2 : {'digit':3},
3 : {'digit':3,'e':4,'E':4},
4 : {'digit':5,'sign':7},
5 : {'digit':5},
6 : {'digit':6,'.':3,'e':4,'E':4},
7 : {'digit':5},
}
let state=0;
for(c of s.trim()) {
if(c>='0' && c<='9') {
c='digit';
}else if(c==='') {
c='blank'
}else if(c==='+' || c==='-') {
c='sign'
}
state=graph[state][c];
if(state===undefined) {
return false;
}
}
if(state==3 || state==5 ||state==6) {
return true
}
return false
};