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
int isMatch(char *s, char *p) { //遞歸出口判斷 if (p[0] == '\0') { return s[0] == '\0'; } //分狀況解決匹配問題,一種帶*一種不帶* if (p[1] == '*') { //帶* while (s[0] != '\0' && (p[0] == '.' || s[0] == p[0])) { //若是匹配成功 if (isMatch(s, p + 2)) { //先把帶*的匹配掠過,對後邊的進行匹配 return 1; } ++s; //把s向後移動一位,而後再次匹配*前的元素(由於*前的元素可能出現屢次) } return isMatch(s, p + 2); //繼續匹配剩下的 } else { //不帶* //若是匹配成功 if (s[0] != '\0' && (p[0] == '.' || s[0] == p[0])) { return isMatch(s + 1, p + 1); //遞歸下一個元素匹配 } else { //沒有匹配成功 return 0; } } }