简繁EN

LeetCodeNo. 009

【LeetCode with Python】 44. Wildcard Matching

目錄

題目

原題頁面:https://leetcode.com/problems/wildcard-matching/
題目型別:Dynamic Programming, Backtracking, Greedy, String
難度評價:Hard
類似題目: (H) Regular Expression Matching

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the **entire** input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

分析

這道動態規劃的題,其特殊test cases造成的麻煩已經遠遠超過動態規劃演算法本身的複雜帶來的麻煩了。之前在最佳化動態規劃演算法時,一直注重的是空間的最佳化,卻沒有考慮到有些cases是可以提前檢測或進行預處理,從而降低執行時間的。如果不這樣做,將一直卡在一些特別長的變態cases上Time Limit Exceeded。

  1. 模式串p中連續的可以預處理合併為一個
  2. 模式串中問號和字元的總數大於字串s的長度時,匹配失敗
  3. 字串s為空時,如果模式串中問號和字元的總數為0(即模式串為空或全是*),則匹配成功,否則匹配失敗

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
if (None == s or '' == s) and (None == p or '' == p):
return True
len_s = len(s)
len_p = len(p)
new_p = ''
last_ch = None
p_solid_char_num = 0
for i in range(0, len_p):
if '*' != last_ch or '*' != p[i]:
new_p += p[i]
last_ch = p[i]
if '*' != p[i]:
p_solid_char_num += 1
if p_solid_char_num > len_s:
return False
isAllStars = True
if (None == s or '' == s) and 0 == p_solid_char_num:
return True
p = new_p
len_p = len(new_p)

F = [[False for j in range(0, len_p + 1)] for i in range(0, 2)]

# 3 cases for True:
# last ch matched, and this ch matcheds (right-down)
# p comes *, and last matched (right)
# last p.ch is *, s comes any ch, and last matched (down)
for i in range(1, len_s + 1):
if 1 == i:
F[0][0] = True
for j in range(1, len_p + 1):
F[0][j] = (F[0][j - 1] and '*' == p[j - 1])
else:
for j in range(0, len_p + 1): # cannot be F[0] = F[1]
F[0][j] = F[1][j]
F[1][0] = False
for j in range(1, len_p + 1):
if True == F[0][j - 1] and (p[j - 1] == s[i - 1] or '?' == p[j - 1] or '*' == p[j - 1]):
F[1][j] = True
elif (True == F[1][j - 1] or True == F[0][j]) and '*' == p[j - 1]:
F[1][j] = True
else:
F[1][j] = False

return F[1][len_p]

本文地址:https://xnerv.wang/zh-tw/leetcode-wildcard-matching/