leetcode.10---Regular Expression Matching

'.' 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

题意:用p指向的正则表达式字符串来判断其是否和s指向的字符串想匹配,其中'.'代表除了'\0'之外的任意一个字符,而若某个字符串后面有*,则表示可以有0个或者多个该字符。

该题可以利用DP,分成三种情况。设当前字符串s和字符串p的下标分别为i,j

1.若p[j]匹配完毕,即p[j]='\0',若p[i]也匹配完毕,则返回true,否则返回false;

2.若p的j+1(即下一个字符)不是*,分三种情况

 (1)若p[j]==s[i],递归验证i+1,j+1

   (2)  若p[i]=='.'且s[i]!='\0',递归验证i+1,j+1

   (3) 否则,返回false

3.若p的j+1(即下一个字符)是*,则不断通过递归回溯i++,j+2

代码如下:

class Solution {
public:
    bool isMatch(string s, string p) {
        return match(s,p,0,0);
    }
    
    bool match(string& s, string& p , int i, int j ){
        if(p[j] == '\0')
             return s[i] == '\0';
             
        if(p[j+1] != '*'){
            if(s[i] != '\0' && (s[i] == p[j] || p[j] == '.'))
                return match(s,p,i+1,j+1);
            else
               return false;
        }else{
            while(s[i] != '\0' && (s[i] == p[j] || p[j] == '.')){
                if(match(s,p,i,j+2))
                    return true;
                i++;
            }
            
            return match(s,p,i,j+2);
        }
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章