Leet Code throw a runtime error but it works fine in my ide, don't know what's wrong


  • 0
    J
    bool isMatch(string s, string p) {
    if (p[0]=='*') {     //illegal syntax
        return false;
    }
    else if(p[0]==s[0]&&s[0]=='\0')  // both empty
        return true;
    else if(p[0]=='\0'&&s[0]!='\0') //rule empty, string not empty
        return false;
    else if(s[0]=='\0'&&p[0]!='\0'){  //string empty, rule not empty
        if(p[1]=='*')
            return isMatch("", p.substr(2,p.length()-2));
        else
            return false;
    }
    else if (p[0]==s[0]||p[0]=='.'){  //process situation two string is both >= 1 bits
        if (p[1]!='*') {
            return isMatch(s.substr(1,s.length()-1), p.substr(1,p.length()-1));
        }
        else {     //.* or c* ( c stand for any character )
            if (p[0]==s[0]) { // c , c*
                for(int i =0;i<=(int)s.length();i++){ //try any possibility of c*
                    if (s[i]==p[0]) {
                        if(!isMatch(s.substr(i,s.length()-i), p.substr(2,p.length()-2)))
                            continue;
                        else
                            return true; //match one of pattern, return true
                    }
                    else{  //encounter a char different from p[0], eliminate c*
                        return isMatch(s.substr(i,s.length()-i), p.substr(2,p.length()-2));
                    }
                    
                }
            }
            else if (p[0]!=s[0]&&p[0]=='.'){ // c, .*
                if (p[3]=='*') {
                    return isMatch(s, ".*"+p.substr(4,p.length()-4));
                }
                for(int i =0;i<=(int)s.length();i++){
                    if(s[i]==p[2]||p[2]=='.'){
                        if(!isMatch(s.substr(i,s.length()-i), p.substr(2,p.length()-2)))
                            continue;
                        else
                            return true;
                    }
                }
                return false; //differ from c,c* , it means p has char that s doesnt have
            }
            else if (p[0]!=s[0]&&p[0]!='.'){ // a, b*
                return isMatch(s, p.substr(2,p.length()-2));
            }
        }
    }
    else if(p[1]=='*')
        return isMatch(s, p.substr(2,p.length()-2));
    else
        return false;
    return false;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.