The questions are as follows:
Implement Regular Expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching shocould cover the entire input string (not partial ).
The function prototype shocould 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
The question intention is very simple, that is, to implement a regular expression matching judgment function. In particular. * This format is not often used. I first thought it was wrong and thought it was a match ". "then ". "What is matched, then * is extended.
In fact, the core idea is a dynamic planning
DP [I] [J] indicates whether the string s [I... Len (s)], p [j... Len (p)] can be matched.
The state transition equation is as follows:
DP [I] [J] =
C1. P [J + 1]! = *. If s [I] = P [J] DP [I] [J] = DP [I + 1] [J + 1]
Else DP [I] [J] = false
C2 P [J + 1] = '*' (in this case, expand *, DP [I] [J], and select a true result from the expansion)
If (s [I] = P [J] | P [J] = '.' & (* s )! = 0) When s [I] and P [J] are the same, for example, ABA, a * B, I = 0, j = 0, which can naturally match a.
If P [J] =. Because it can match any character, there is basically the same way as equality.
In addition, the value of I is incremented for each step of matching. If yes, true is returned. Otherwise, the result after the completion of wildcard matching is returned.
The Code is as follows:
#include <stdio.h>class Solution {public:bool isMatch(const char *s, const char *p) {// Start typing your C/C++ solution below// DO NOT write int main() function if( 0 == *p) return 0 == *s;if(*(p+1) != '*'){if(*p == *s || (*p) == '.' && (*s) != 0){return isMatch(s+1, p+1);}return false;}else{while(*p == *s || ((*p) == '.' && (*s) != 0)){if(isMatch(s, p + 2)){return true;}s++;}return isMatch(s, p + 2);}}};