Time limit error


  • 0
    F

    Here is a solution translated from Java to C++, but there is time limit error.
    Last executed input: "baccbbcbcacacbbc", "c*.bcbabb.a*"

    I do not know why.

    class Solution {
    public:
        bool matching(string s, string p) {
            if (p.length() == 0) {
                return s.length() == 0;
            }
            if (p.length() == 1) {
                if (s.length() < 1) {
                    return false;
                }
                else if ((s[0] != p[0]) && (p[0] != '.')) {
                    return false;
                }
                else {
                    return matching(s.substr(1, s.length()-1), p.substr(1, p.length()-1));
                }
            }
            if (p[1] != '*') {
                if (s.length() < 1) {
                    return false;
                }
                if ((s[0] != p[0]) && (p[0] != '.')) {
                    return false;
                }
                else {
                    return matching(s.substr(1, s.length()-1), p.substr(1, p.length()-1));
                }
            }
    
            else {
                if (matching(s, p.substr(2, p.length()-2))) {
                    return true;
                }
                int i = 0;
                while (i < s.length() && (s[i] == p[0] || p[0] == '.')) {
                    if (matching(s.substr(i+1, s.length()-i-1), p.substr(2, p.length()-2))) {
                        return true;
                    }
                    i++;
                }
                return false;
            }
        }
        bool isMatch(const char *s, const char *p) {
            string s_str = string(s);
            string p_str = string(p);
            return matching(s_str, p_str);
        }
    
    };

Log in to reply
 

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