有效数字(按顺序)可以分成以下几个部分:
- 一个 小数 或者 整数
- (可选)一个 ‘e’ 或 ‘E’ ,后面跟着一个 整数
小数(按顺序)可以分成以下几个部分:
- (可选)一个符号字符(’+’ 或 ‘-‘)
- 下述格式之一:
- 至少一位数字,后面跟着一个点 ‘.’
- 至少一位数字,后面跟着一个点 ‘.’ ,后面再跟着至少一位数字
- 一个点 ‘.’ ,后面跟着至少一位数字
整数(按顺序)可以分成以下几个部分:
- (可选)一个符号字符(’+’ 或 ‘-‘)
- 至少一位数字
部分有效数字列举如下:[“2”, “0089”, “-0.1”, “+3.14”, “4.”, “-.9”, “2e10”, “-90E3”, “3e+7”, “+6e-1”, “53.5e93”, “-123.456e789”]
部分无效数字列举如下:[“abc”, “1a”, “1e”, “e3”, “99e2.5”, “–6”, “-+3”, “95a54e53”]
给你一个字符串 s ,如果 s 是一个 有效数字 ,请返回 true 。
示例 1:
输入:s = "0"
输出:true
示例 2:
输入:s = "e"
输出:false
示例 3:
输入:s = "."
输出:false
提示:
- 1 <= s.length <= 20
- s 仅含英文字母(大写和小写),数字(0-9),加号 ‘+’ ,减号 ‘-‘ ,或者点 ‘.’ 。
解题:
func isNumber(s string) bool {
pattern := `^[+-]?((\d+\.?)|(\d*\.\d+))([eE][+-]?\d+)?$`
ok, _ := regexp.MatchString(pattern, s)
return ok
}
正则匹配效率是真的差
官方解答:
1.确定有限状态自动机
type State int
type CharType int
const (
StateInitial State = iota
StateIntSign
StateInteger
StatePoint
StatePointWithoutInt
StateFraction
StateExp
StateExpSign
StateExpNumber
StateEnd
)
const (
CharNumber CharType = iota
CharExp
CharPoint
CharSign
CharIllegal
)
func toCharType(ch byte) CharType {
switch ch {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
return CharNumber
case 'e', 'E':
return CharExp
case '.':
return CharPoint
case '+', '-':
return CharSign
default:
return CharIllegal
}
}
func isNumber(s string) bool {
transfer := map[State]map[CharType]State{
StateInitial: map[CharType]State{
CharNumber: StateInteger,
CharPoint: StatePointWithoutInt,
CharSign: StateIntSign,
},
StateIntSign: map[CharType]State{
CharNumber: StateInteger,
CharPoint: StatePointWithoutInt,
},
StateInteger: map[CharType]State{
CharNumber: StateInteger,
CharExp: StateExp,
CharPoint: StatePoint,
},
StatePoint: map[CharType]State{
CharNumber: StateFraction,
CharExp: StateExp,
},
StatePointWithoutInt: map[CharType]State{
CharNumber: StateFraction,
},
StateFraction: map[CharType]State{
CharNumber: StateFraction,
CharExp: StateExp,
},
StateExp: map[CharType]State{
CharNumber: StateExpNumber,
CharSign: StateExpSign,
},
StateExpSign: map[CharType]State{
CharNumber: StateExpNumber,
},
StateExpNumber: map[CharType]State{
CharNumber: StateExpNumber,
},
}
state := StateInitial
for i := 0; i < len(s); i++ {
typ := toCharType(s[i])
if _, ok := transfer[state][typ]; !ok {
return false
} else {
state = transfer[state][typ]
}
}
return state == StateInteger || state == StatePoint || state == StateFraction || state == StateExpNumber || state == StateEnd
}