Simple C++ Solution Using Recursion


  • 0
    M
    class Solution {
    public:
        bool IsMatch(char const * s, char const * r) {
            if (!*s && !*r) return true;
            if (*s && !*r) return false;
            bool is_mult = *(r + 1) == '*', is_any = *r == '.';
            if (is_mult) {
                while (*s && (is_any || *s == *r)) {
                    if (IsMatch(s, r + 2)) return true;
                    ++s;
                }
                return IsMatch(s, r + 2);
            } else {
                if (!(*s && (is_any || *s == *r))) return false;
                return IsMatch(s + 1, r + 1);
            }
        }
        bool isMatch(string s, string p) {
            return IsMatch(s.c_str(), p.c_str());
        }
    };
    

Log in to reply
 

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