請實現一個函數用來匹配包括'.'和'*'的正則表達式。模式中的字符'.'表示任意一個字符,而'*'表示它前面的字符能夠出現任意次(包含0次)。 在本題中,匹配是指字符串的全部字符匹配整個模式。例如,字符串"aaa"與模式"a.a"和"ab*ac*a"匹配,可是與"aa.a"和"ab*a"均不匹配正則表達式
用動態規劃來解決算法
規定數組
若,則str[0~i-1]和pattern[0~j-1]匹配函數
一、當p[j-1] != * 時spa
二、當p[j-1] = * 時3d
記p[j-2]=X,分爲如下兩種狀況code
(a) "X*"重複了0次:等式右邊第一項說明*重複零次,則f[i][j]與 f[i][j-2]真假相同,亦或是p[j-2]是萬能字符blog
(b)"X*"重複了大於等於1次:字符串
等式右邊第一項說明要麼是萬能字符,input
第二項表示f[i][j]與f[i-1][j]真假相同,其實就是回退到重複0次的狀況
第三項保證複製的正確性
如 s=bcaaa p=bca* f[5][4] -> f[4][4] -> f[3][4] -> f[2][4]
此時 s = bc p = bca*,能夠匹配
算法流程
一、初始化二維布爾數組,注意列不必定爲0
二、按以上規則自下網上計算出f[i][j]
計算過程
空 | b | c | a | a | a | |
空 | 1 | 0 | 0 | 0 | 0 | 0 |
b | 0 | 1 | 0 | 0 | 0 | 0 |
c | 0 | 0 | 1 | 0 | 0 | 0 |
a | 0 | 0 | 0 | 1 | 0 | 0 |
* | 0 | 0 | 1 | 1 | 1 | 1 |
class Solution { public: bool match(char* str, char* pattern) { int m = strlen(str); int n = strlen(pattern); vector<vector<bool>> f(m+1, vector<bool>(n+1, false)); f[0][0] = true; for (int i = 1; i <= m; i++) { f[i][0] = false; } for (int j = 1; j <= n; j++) { f[0][j] = ((j > 1) && (pattern[j-1] == '*') && (f[0][j-2])); } for (int i = 1; i <= m; i++){ for (int j = 1; j <= n; j++){ if (pattern[j-1] != '*') f[i][j] = f[i - 1][j - 1] && (str[i - 1] == pattern[j - 1] || '.' == pattern[j - 1]); else f[i][j] = f[i][j-2] || (pattern[j-2] == '.') || (str[i-1] == pattern[j-2]) && f[i-1][j]; } } return f[m][n]; } };
Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
.
'?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence).
Example 1:
Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input: s = "acdcb" p = "a*c?b" Output: false
class Solution { public: bool isMatch(string s, string p) { int n = (int)s.length(); int m = (int)p.length(); vector<vector<bool>> dp(n + 1, vector<bool>(m + 1)); dp[0][0] = true; for (int i = 1; i <= m && p[i - 1] == '*'; i++) dp[0][i] = true; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (p[j - 1] == '*') dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; else dp[i][j] = (p[j - 1] == '?' || s[i - 1] == p[j - 1]) && dp[i - 1][j - 1]; } } return dp[n][m]; } };