Problem: implement regular expression matching with support '. '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 shoshould 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
It is a regular expression. You can refer to Baidu to learn the regular expression first. * Indicates that the first character appears zero or multiple times. For example, Zo * can match Z because * indicates that the preceding character o appears zero times, so it matches Z. Similarly, Zo * can also match Zo, zoo, zoooo, zooooooo, and so on. The dot '.' Is a wildcard that matches any single character. Then, the star '. *' can match any number of characters, because * indicates any number of duplicates in the front. So it is the repetition of multiple '.', and '.' is an arbitrary match, so any combination can be used. The first point matches a. The second point does not only match a, but can also match any character. So '. *' is omnipotent. I should have not understood the error. After a long time, I did not think of a good idea and had to use recursion.
class Solution {public:bool isMatch(const char *s, const char *p){ if(s == NULL || p == NULL) return false; if (*p == ‘\0‘) return *s == ‘\0‘; if (*(p + 1) == ‘*‘) { while(*s == *p || *p == ‘.‘ && *s != ‘\0‘) { if (isMatch(s, p + 2)) return true; s++; } return isMatch(s, p + 2); } else if (*s == *p || *p == ‘.‘&&*s!=‘\0‘) return isMatch(s + 1, p + 1); return false;}};
Submit multiple attempts to put if (* P = '\ 0 ')Return * s = '\ 0 ';Ignore. Because it is recursive, it cannot be left blank.
Question 10 of leetcode -- Regular Expression matching