标签:
这道题直观想法是用dp 复杂度 O(mn) 代码如下, 但是在用python的时候会超时
class Solution: # @param {string} s # @param {string} p # @return {boolean} def isMatch(self, s, p): m, n = len(p), len(s) dp = [False for i in range(0, n+1)] dp[0] = True for j in range(1,n+1): dp[j] = False for i in range(1, m+1): dpTemp = dp[:] if p[i-1] == ‘*‘: dp[0] = dpTemp[0] else: dp[0] = False isThereMatch = dpTemp[0] for j in range(1,n+1): isThereMatch = isThereMatch or dpTemp[j] if p[i-1] != ‘*‘: if p[i-1] == ‘?‘: dp[j] = dpTemp[j-1] else: dp[j] = (p[i-1]==s[j-1] and dpTemp[j-1]) else: dp[j] = isThereMatch return dp[n]
这道题有另外一个方法,比较巧妙, 具体复杂度我觉得是介于O(mn) 和 O(m+n)的范围内, 最后运行时间120ms 属于用python 里面最快的了, 方法很巧妙,临时很难想到。
class Solution: # @param s, an input string # @param p, a pattern string # @return a boolean def isMatch(self, s, p): s_cur, p_cur, starPos, lastMatch = 0, 0, -1, 0 while s_cur<len(s): if p_cur< len(p) and (s[s_cur]==p[p_cur] or p[p_cur]==‘?‘): s_cur, p_cur = s_cur + 1, p_cur + 1 elif p_cur < len(p) and p[p_cur]==‘*‘: lastMatch = s_cur starPos = p_cur p_cur += 1 elif starPos != -1 : p_cur = starPos+1 lastMatch = lastMatch+1 s_cur = lastMatch else: return False while p_cur<len(p) and p[p_cur]==‘*‘: p_cur = p_cur+1 return p_cur == len(p)
标签:
原文地址:http://www.cnblogs.com/dapanshe/p/4649978.html