Difference between the two codes


  • 0
    S

    This is the code that works :

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int sLen = s.length(); 
            int pLen = p.length(); 
            if(p.empty()) return s.empty();
            
            if(p.at(pLen-1)=='*')
            { 
                if(sLen>0 && (p.at(pLen-2)=='.' || s.at(sLen-1)==p.at(pLen-2))){return (isMatch(s, p.substr(0, pLen-2)) || isMatch(s.substr(0, sLen-1), p) );}
                else return isMatch(s, p.substr(0, pLen-2)); 
            }
            else
            {
                if(sLen>0 && (s.at(sLen-1)==p.at(pLen-1) || p.at(pLen-1)=='.')) return isMatch(s.substr(0, sLen-1), p.substr(0, pLen-1)); //difference is here
                else return false;
            } 
        }
    };
    

    But this one does not :

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int sLen = s.length(); 
            int pLen = p.length(); 
            if(p.empty()) return s.empty();
            
            if(p.at(pLen-1)=='*')
            { 
                if(sLen>0 && (p.at(pLen-2)=='.' || s.at(sLen-1)==p.at(pLen-2))){return (isMatch(s, p.substr(0, pLen-2)) || isMatch(s.substr(0, sLen-1), p) );}
                else return isMatch(s, p.substr(0, pLen-2)); 
            }
            else
            {
                if((s.at(sLen-1)==p.at(pLen-1) || p.at(pLen-1)=='.') && sLen>0) return isMatch(s.substr(0, sLen-1), p.substr(0, pLen-1)); //difference is here
                else return false;
            } 
        }
    };
    

    The main difference between the two code being the " if " condition highlighted above.
    Could anyone please explain why.


Log in to reply
 

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