converting a*b* regular expression to finite state machine

只谈情不闲聊 提交于 2020-01-26 04:31:04

问题


How can I convert the regular expression a*b* to a finite state machine? I am just starting out, and have no idea how to start.


回答1:


Think about it. a*b* means a 0 or more times then b 0 or more times.

Building a state transition table...

Transitions
0 - empty
1 - next a
2 - next b
3 - next not ( a or b )

State / Transitions
S | T | S
S | 0 | Y
S | 1 | a
S | 2 | b
S | 3 | N
a | 0 | Y
a | 1 | a
a | 2 | b
a | 3 | N
b | 0 | Y
b | 1 | N
b | 2 | b
b | 3 | N

States
S - start
Y - end - matches
N - end - doesn't match
a - is matchng a+
b - is matching b+

You can then go code this in whatever language you like. Some pseudo code...

char state = 'S';
string s = gets(); // assume a 0 terminated string
for( int i = 0; ; i++ )
{
state = table[state][getTransition(s[i])];
if(state in ['Y','N']) break;
}

int getTransition(char c) { if c == 0 return 0; if c == 'a' return 1; if c == 'b' return 2; return 3; }


来源:https://stackoverflow.com/questions/51453230/converting-ab-regular-expression-to-finite-state-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!