【无标题】

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")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值