10.Regular Expression Matching (String; DFS)

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

 

class Solution {

public:

    bool isMatch(string s, string p) {

   //     if (s == NULL || p == NULL) 

//            return false;

        return dfsIsMatch(s,p,0,0);

    

    }

    

    bool dfsIsMatch(const string& s, const string& p, int sIndex, int pIndex){

        if (p[pIndex] == '\0') //结束条件:s若是'\0',p必须也是'\0'

            return  s[sIndex] == '\0';

        

        if (p[pIndex+1] == '*') {

            /* '.' means any character (except '\0')

             * '.' means repeat 0 or more times

             * '.*' means repeat '.' 0 or more times

             */ 

            while ((s[sIndex] != '\0' && p[pIndex] == '.') || s[sIndex] == p[pIndex]) { //'.'可以与除'\0'以外的任何字符匹配

                if (dfsIsMatch(s, p, sIndex, pIndex+2)) //p[pIndex] repeat 0 times

                    return true;



                sIndex += 1;//p[pIndex]在原基础上repeat次数+1

            }

            

            return dfsIsMatch(s, p, sIndex, pIndex+2); //when s[sIndex] != p[pIndex] && p[pIndex] != '.'(此时只有s[sIndex]==p[pIndex]=='\0'时可能return true)

        } 

        else if ((s[sIndex] != '\0' && p[pIndex] == '.') || s[sIndex] == p[pIndex]) {

            return dfsIsMatch(s, p, sIndex + 1, pIndex + 1);

        }

       

        return false;

    }

};

 

你可能感兴趣的:(10.Regular Expression Matching (String; DFS))