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", "c*a*b") → true
这个跟之前多校有道题很像,除了"."的匹配不一样。
#include <iostream> #include <algorithm> #include <string.h> #include <vector> #include <sstream> #include <stdio.h> using namespace std; bool isMatch(const string& s, const string& p) { int slen = s.size(); int plen = p.size(); //dp[i + 1][j + 1]表示 s[i]跟p[j]当前的匹配情况 /** * bp[i + 1][j + 1]: if s[0..i] matches p[0..j] * if p[j] != '*' * bp[i + 1][j + 1] = bp[i][j] && s[i] == p[j] * if p[j] == '*', denote p[j - 1] with x, * then bp[i + 1][j + 1] is true iff any of the following is true * 1) "x*" repeats 0 time and matches empty: bp[i + 1][j -1] * 2) "x*" repeats 1 time and matches x: bp[i + 1][j] * 3) "x*" repeats >= 2 times and matches "x*x": s[i] == x && bp[i][j + 1] * '.' matches any single character 可以画一个方格图,就像最长公共子序列一样,就比较好理解了 */ bool dp[slen + 1][plen + 1]; dp[0][0] = 1; for (int i = 0; i < slen; ++i) { dp[i + 1][0] = 0; } for (int i = 0; i < plen; ++i) { dp[0][i + 1] = i > 0 && p[i] == '*' && dp[0][i - 1]; } for (int i = 0; i < slen; ++i) { for (int j = 0; j < plen; ++j) { if (p[j] == '*') { //x*匹配0个x的时候 x*匹配1个x的时候 x*匹配>=2个x的时候 x*x dp[i + 1][j + 1] = (j > 0 && dp[i + 1][j - 1]) || dp[i + 1][j] || (dp[i][j + 1] && j > 0 && (p[j - 1] == '.' || s[i] == p[j - 1])); } else { dp[i + 1][j + 1] = dp[i][j] && (s[i] == p[j] || p[j] == '.'); } } } return dp[slen][plen]; } int main() { cout << isMatch("aab", "c*a*b") << endl;; }