状态机fsm_干货|你真的了解有限状态机(FSM)算法的使用方法吗?

a74b73c645bc5d4c5533e7899dc248b3.png

由于我以前是从事路由协议开发,所以对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

状态机一般有两种写法:横着写和竖着写。横着写是在事件中判断状态。竖着写是在状态中判断事件。这两种写法是等效的,但在实际操作中,效果有点诧异,但各有优缺点。

我们来分析一个Leetcode上通过率最低的算法题,第65题---Valid Number,来感受一下FSM的强大威力。

题目如下:

Validate if a given string can be interpreted as a decimal number.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值