题目类型有点新颖,有限状态机
// CharType表示当前字符的类型
// State表示当前所处的状态
type State int
type CharType int
const (
CHAR_SPACE CharType = iota
CHAR_POINT
CHAR_NUMBER
CHAR_ECHAR
CHAR_SINGAL
CHAR_INVALID
)
func getType(ch byte) CharType {
switch(ch){
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
return CHAR_NUMBER
case '.':
return CHAR_POINT
case '+', '-':
return CHAR_SINGAL
// case ' ':
// return CHAR_SPACE
case 'e', 'E':
return CHAR_ECHAR
}
return CHAR_INVALID
}
const (
STATE_INIT State = iota
STATE_INIT_POINT
STATE_INIT_SINGAL
STATE_NUMBER
STATE_NUMBER_POINT
STATE_POINT_NUMBER
STATE_ECHAR
STATE_ECHAR_NUMBER
STATE_ECHAR_SINGAL
)
func isNumber(s string) bool {
tranfer := map[State]map[CharType]State{
STATE_INIT: {
CHAR_SINGAL: STATE_INIT_SINGAL,
CHAR_POINT: STATE_INIT_POINT,
CHAR_NUMBER: STATE_NUMBER,
},
STATE_INIT_POINT: {
CHAR_NUMBER: STATE_POINT_NUMBER,
},
STATE_NUMBER: {
CHAR_NUMBER: STATE_NUMBER,
CHAR_POINT: STATE_NUMBER_POINT,
CHAR_ECHAR: STATE_ECHAR,
},
STATE_INIT_SINGAL: {
CHAR_POINT: STATE_INIT_POINT,
CHAR_NUMBER: STATE_NUMBER,
},
STATE_ECHAR: {
CHAR_SINGAL: STATE_ECHAR_SINGAL,
CHAR_NUMBER: STATE_ECHAR_NUMBER,
},
STATE_NUMBER_POINT: {
CHAR_NUMBER: STATE_POINT_NUMBER,
CHAR_ECHAR: STATE_ECHAR,
},
STATE_POINT_NUMBER: {
CHAR_NUMBER: STATE_POINT_NUMBER,
CHAR_ECHAR: STATE_ECHAR,
},
STATE_ECHAR_NUMBER: {
CHAR_NUMBER: STATE_ECHAR_NUMBER,
},
STATE_ECHAR_SINGAL: {
CHAR_NUMBER: STATE_ECHAR_NUMBER,
},
}
state := STATE_INIT
ss := strings.TrimSpace(s)
for i := range ss {
ch := ss[i]
ty := getType(ch)
if ty == CHAR_INVALID {
return false
}
if st, ok := tranfer[state][ty]; ok {
state = st
} else {
return false
}
}
switch state {
case STATE_NUMBER, STATE_POINT_NUMBER, STATE_NUMBER_POINT, STATE_ECHAR_NUMBER:
return true
}
return false
}