![a74b73c645bc5d4c5533e7899dc248b3.png](https://i-blog.csdnimg.cn/blog_migrate/52cfeafba2601557cf371b4043e78ad0.jpeg)
由于我以前是从事路由协议开发,所以对FSM比较熟悉,因为网络协议RFC文档里面有大量的关于状态机的描述。偶然一次在知乎上看到一个算法题,不少回答说可以通过DFA来解决,最初以为是一个更高级的解法,当看到别人画的转换图后,觉得跟FSM没有区别,然后就百度了一下DFA和FSM的关系。wikipidia是这样描述的:
Finite state machines are of two types – deterministic finite state machines and non-deterministic finite state machines.
In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)—also known as deterministic finite acceptor (DFA), deterministic finite state machine (DFSM), or deterministic finite state automaton (DFSA)—is a finite-state machine that accepts or rejects strings of symbols and only produces a unique computation (or run) of the automaton for each input string.
从以上描述应该明白了FSM和DFA的关系,也就是全集与子集的关系。
如果简单一点描述FSM,可以这样理解:有限状态机的工作原理是,当事件(event)发生后,根据当前状态(current_state) ,决定执行的动作(action),并设置下一个状态(next_state)。
一般用二维表来描述其逻辑关系,见下图:
![2b7165c295f7e2d0857161cd33b043e9.png](https://i-blog.csdnimg.cn/blog_migrate/2e4adcda949adf2235266917e19c3a78.jpeg)
状态机一般有两种写法:横着写和竖着写。横着写是在事件中判断状态。竖着写是在状态中判断事件。这两种写法是等效的,但在实际操作中,效果有点诧异,但各有优缺点。
我们来分析一个Leetcode上通过率最低的算法题,第65题---Valid Number,来感受一下FSM的强大威力。
题目如下:
Validate if a given string can be interpreted as a decimal number.