Leetcode:正则表达式.

来源:互联网 发布:小明发布永久域名台湾 编辑:程序博客网 时间:2024/06/16 01:55

这题比较难,需要采取递归下降的方式来解析数据,并处理边界问题。

class Solution(object):    def isMatch(self, s, p):        print(s,p,'...')        i,n = 0,len(p)        if s=='':return p=='' or (len(p)>=2 and p[1]=='*' and self.isMatch('',p[2:]))        if p=='':return False        if len(p)==1:return (s[0]==p[0] or p[0]=='.') and self.isMatch(s[1:],p[1:])        if s[-1]!=p[-1] and p[-1]!='.' and p[-1]!='*' :return False        ch = p[0]        if ch=='.':            if p[1]=='*':                j,n_s = 0,len(s)                while j<n_s+1:                    res = self.isMatch(s[j:],p[2:])                    if res==False:pass                    else:return True                    j+=1                return False            else:#p[i+1] is normal charcter                return  self.isMatch(s[1:],p[1:])        else:#normal charcter            if p[1]=='*':#match 0 or more                j = 0                n_s = len(s)-1                while j<=n_s+1:                    if (j>0 and s[j-1]!=ch):break;                    print(j,s,p,ch,s[j-1],n_s)                    res = self.isMatch(s[j:],p[2:])                    if res==False:pass                    else:return True                    j+=1                return False            else:                return ch==s[0] and self.isMatch(s[1:],p[1:])print(Solution().isMatch("ab","a*"))
0 0
原创粉丝点击