Wildcard Matching
字符串的模式匹配,类似正则
总体思想:
把模式串按照 * 分割成字串,如果匹配串中按顺序分布着这些字串,那么就OK
本着这个思想实现的是:贪心算法
方法一,用字串比较的方法:
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
n = len(s)
psplit = p.split("*")
# No "*"
if len(psplit) == 1:
if n == len(p) and self.strMatch(s, psplit[0]):
return True
else:
return False
# Delete "" in psplit
pPureList = [x for x in psplit if x]
# Length compare
pPureStr = "".join(pPureList)
if len(pPureStr) > n: return False
# Head is not "*"
if p[0] != "*":
if not self.strMatch(s[:len(pPureList[0])], pPureList[0]):
return False
# Tail is not "*"
if p[-1] != "*":
if not self.strMatch(s[n-len(pPureList[-1]):], pPureList[-1]):
return False
i = 0
for one in pPureList:
oneLen = len(one)
while oneLen + i <= n and not self.strMatch(s[i:i+oneLen], one):
i += 1
if oneLen + i > n:
return False
else:
i += oneLen
return True
def strMatch(self, a, b):
# a and b is same lenght, only b has "?"
i = 0
n = len(a)
while i < n:
if b[i] != "?" and a[i] != b[i]:
return False
i += 1
return True
方法二,脚标控制,参考了Discuss里面的思想:
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
ns, np = len(s), len(p)
i, j, ni, nj = 0, 0, 0, -1
while i < ns:
if j < np and (p[j] == "?" or s[i] == p[j]):
i, j = i+1, j+1
elif j < np and p[j] == "*":
ni, nj = i, j+1
j += 1
elif nj != -1:
ni += 1
i, j = ni, nj
else:
return False
while j < np and p[j] == "*":
j += 1
return j == np