处理浮点数的状态机
這個問題來自于 leetcode 065:?
Valid Number
?
如果用正則表達式來寫一個浮點數的解析,大概是這樣的:
?
[+-]?(([0-9]+\.?) | (\.[0-9]))[0-9]*([eE][+-]?[0-9]+)?
我自己使用 dot 畫了一個狀態機出來:
?
?
如果編寫代碼來模擬這個狀態機,可以拆分為 “eE" 前后兩部分分開處理; “eE” 前面的部分,還可以拆成 “.” 前后兩部分(如果有點)來編寫。
這道題目在 leetcode 上難度為 Hard,可以看出來這種不起眼的小細節,更能考驗基本功。
?
------------------
由于字數限制,附上我話這個狀態機使用的源碼:
1 digraph { 2 graph [fontname = "Microsoft YaHei",fontsize=16 ranksep=1.0 splines=1 overlap=false size="16, 16" compound=true] 3 edge [fontname = "Microsoft YaHei",fontsize=16] 4 node [fontname = "Microsoft YaHei",fontsize=16 weight=2 rank=same width=1 rankdir=LR] 5 6 p0[label="Start"] 7 p2[label="Initial-Check"] 8 p4[label="Dot-First"] 9 p5[label="After-E"] 10 p6[label="After-E-Mark"] 11 p7[label="Almost-Done"] 12 p8[label="End"] 13 p9[label="Sign-Mark"] 14 pa[label="After-Dot"] 15 16 17 p0 -> p9[label="[+-]"] 18 p0 -> p9[label="blank-string"] 19 20 p9 -> p4[label="``.''"] 21 22 p9 -> p2[label="[0-9]"] 23 24 p2 -> p2[label="[0-9]"] 25 p2 -> pa[label="``.''"] 26 p2 -> pa[label="blank-string"] 27 p4 -> pa[label="[0-9]"] 28 pa -> pa[label="[0-9]"] 29 pa -> p8[label="$"] 30 pa -> p5[label="[Ee]"] 31 p5 -> p6[label="[+-]"] 32 p5 -> p6[label="blank-string"] 33 p6 -> p7[label="[0-9]"] 34 p7 -> p7[label="[0-9]"] 35 p7 -> p8[label="$"] 36 }?
轉載于:https://www.cnblogs.com/llhf/p/4728758.html
總結
- 上一篇: 怎么在泰山上进行绘画写生?
- 下一篇: 怎么在泰山上进行摄影创作?