約 3 分鐘212 字484 個單字
題目
原題頁面:https://leetcode.com/problems/regular-expression-matching/
題目型別:Dynamic Programming, Backtracking, String
難度評價:Hard
類似題目:(H) Wildcard Matching
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
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", "a*") → true
isMatch("aa", ".") → true
isMatch("ab", ".") → true
isMatch("aab", "cab") → true
分析
和Wildcard Matching這道題類似,動態規劃演算法本身已經不是難點,關鍵在於最好對一些特殊cases做預處理:
模式串p中連續的對可以合併成一個,如aa可以合併為a,而..也可以合併為.(下面的程式碼裡算出了合併後的new_p_arr,但DP用的還是原來的p_arr,沒用上它)
模式串p中實體字元(不帶)的個數大於字串s的長度時,匹配失敗
模式串p中沒有任何實體字元,而字串s長度為0時,匹配成功
此外,目前用的解法已經將使用到的DP矩陣減小到了兩行,最多還能繼續最佳化到一行加一個臨時變數,做不到2*2的小矩陣。
程式碼
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class Solution:
class Item: def __init__(self, char, symbol): self.char = char self.symbol = symbol
def splitStr(self, str): items = [ ] index = 0 len_str = len(str) while index < len_str: if index + 1 >= len_str or '*' != str[index + 1]: items.append(Solution.Item(str[index], '')) index += 1 else: items.append(Solution.Item(str[index], '*')) index += 2 return items
def isMatch(self, s, p): if '' == s and '' == p: return True p_arr = self.splitStr(p) len_s = len(s) len_p_arr = len(p_arr)
last_item = Solution.Item(None, None) p_char_num = 0 new_p_arr = [ ] for i in range(0, len_p_arr): if last_item.char == p_arr[i].char and last_item.symbol == p_arr[i].symbol and '*' == p_arr[i].symbol: pass else: new_p_arr.append(p_arr[i]) last_item = p_arr[i] if '' == p_arr[i].symbol: p_char_num += 1 if p_char_num > len_s: return False if 0 ==p_char_num and 0 == len_s: return True
F = [[False for j in range(0, len_p_arr + 1)] for i in range(0, 2)]
for i in range(1, len_s + 1): if 1 == i: F[0][0] = True for j in range(1, len_p_arr + 1): F[0][j] = (F[0][j - 1] and '*' == p_arr[j - 1].symbol) else: for j in range(0, len_p_arr + 1): F[0][j] = F[1][j] F[1][0] = False for j in range(1, len_p_arr + 1): if True == F[0][j - 1] and (p_arr[j - 1].char == s[i - 1] or '.' == p_arr[j - 1].char): F[1][j] = True elif True == F[1][j - 1] and '*' == p_arr[j - 1].symbol: F[1][j] = True elif True == F[0][j] and (s[i - 1] == p_arr[j - 1].char or '.' == p_arr[j - 1].char)and '*' == p_arr[j - 1].symbol: F[1][j] = True else: F[1][j] = False
return F[1][len_p_arr]
|
本文地址:https://xnerv.wang/zh-tw/leetcode-regular-expression-matching/