LeetCode第8题: 字符串转换整数 (atoi).
本地可以用动态规划求解,先贴上官方的状态转移图片
这样我们可以直接去写代码了,非常简单
import (
"math"
"strconv"
)
// ' ' +/- number other
// start start signed in_number end
// signed end end in_number end
// in_number end end in_number end
// end end end end end
var statusTable = [][]int {
{0, 1, 2, 3},
{3, 3, 2, 3},
{3, 3, 2, 3},
{3, 3, 3, 3},
}
const (
start = 0
signed = 1
in_number = 2
end = 3
space = 0
sign = 1
number = 2
other = 3
)
func myAtoi(str string) int {
result := 0
nowStatus := start
positiveorNegative := true
for _, s := range str {
nowStatus = getStatus(nowStatus, s)
if nowStatus == end {
break
} else if nowStatus == signed {
if s == '-' {
positiveorNegative = false
}
} else if nowStatus == in_number {
result = result * 10 + str2Num(string(s))
if (result > math.MaxInt32 && positiveorNegative) || (!positiveorNegative && result < math.MinInt32) {
if positiveorNegative {
return math.MaxInt32
} else {
return math.MinInt32
}
}
}
}
if positiveorNegative {
if result > math.MaxInt32 {
return math.MaxInt32
}
return result
} else {
if -result <= math.MinInt32 {
return math.MinInt32
}
return -result
}
}
func getStatus(beforeStatus int, s int32) int { // 根据上次状态和现在的字符返回当前的状态
var sType int
if s == ' ' {
sType = space
} else if s == '-' || s == '+' {
sType = sign
} else if s >= '0' && s <= '9' {
sType = number
} else {
sType = other
}
return statusTable[beforeStatus][sType]
}
func str2Num(str string) int {
if intStr, err := strconv.Atoi(str); err == nil {
return intStr
}
return -1
}