class Automata:
def __init__(self, p):
self.transit_tokens = []
self.loop_tokens = {}
i = 0
while i + 1 < len(p):
if p[i + 1] == '*':
cur_state = len(self.transit_tokens)
if cur_state in self.loop_tokens:
self.loop_tokens[cur_state] += p[i]
else:
self.loop_tokens[cur_state] = p[i]
self.transit_tokens.append('')
i += 2
else:
self.transit_tokens.append(p[i])
i += 1
if i < len(p): self.transit_tokens.append(p[i])
self.state_cnt = len(self.transit_tokens)
self.compute_epsilon_closure()
self.states = self.epsilon_closure[0]
def compute_epsilon_closure(self):
self.epsilon_closure = [{state} for state in range(self.state_cnt + 1)]
for i in reversed(range(self.state_cnt)):
if self.transit_tokens[i] == '':
self.epsilon_closure[i] = self.epsilon_closure[i].union(self.epsilon_closure[i + 1])
print(self.epsilon_closure)
def run(self, symbol):
new_states = set()
for state in self.states:
if state < self.state_cnt and (symbol in self.transit_tokens[state] or '.' in self.transit_tokens[state]):
new_states.add(state + 1)
if state in self.loop_tokens and (symbol in self.loop_tokens[state] or '.' in self.loop_tokens[state]):
new_states.add(state)
new_states = new_states.union(*[self.epsilon_closure[new_state] for new_state in new_states])
print(self.states, symbol, new_states)
self.states = new_states
return new_states
class Solution:
def isMatch(self, s, p):
if len(s) == 0 and len(p) == 0: return True
if len(s) != 0 and len(p) == 0: return False
dfa = Automata(p)
for c in s:
states = dfa.run(c)
if len(states) == 0: return False
return (dfa.state_cnt in dfa.states)
a=Solution()
print a.isMatch("a","aa*ab")
【无标题】
最新推荐文章于 2024-11-17 20:27:16 发布