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);
        }
    }
};



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