Output of OJ doesn't match with my own machine's


  • 0
    W

    This is my code. I run it on my pc and its result is false. However OJ report it as true...

    #include <iostream>
    #include <string>
    using namespace std;
    class Solution {
    public:
        bool isMatch(string s, string p) {
            bool d[s.size()+1][p.size()+1];
            for(int i = 0; i <= s.size(); i++){
                d[i][0] = false;
            }
            for(int j = 0; j <= p.size(); j++){
                if(p[1]!='*')
                    d[0][j] = false;
                else if(p.size()==2)
                    d[0][j] = true;
                    
            }
            d[0][0] = true;
            for(int i = 1; i <= s.size(); i++){
                for(int j = 1; j <= p.size(); j++){
                    if(p[j-1] != '*') // "abc" "abc" => "ab" "ab"; "abc" "ab." => "ab" "ab"
                        d[i][j] = d[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.');
                    else{
                        if(d[i][j-1] == 1) d[i][j] = true;// "abc" "abc*" => "abc" "abc"; "ab" "a.*" => "ab" "a."; * repeat 1 time of previous char to match string s
                        if(j >= 2 && d[i][j-2] == 1) d[i][j] = true;// "ab" "abc*" => "ab" "ab"; * repeat 0 time of previous char to match string s
                        if(d[i-1][j] == 1 && (s[i-1] == p[j-2]||(p[j-2]=='.'))) d[i][j] = true;//"abb" "ab*" => "ab" "ab*"; "abc" "a.*" * repeat more than 1 time of previous char to match string s
                    }
                }
            }
            return d[s.size()][p.size()];
        }
    };
    int main(){
        string s = "aaba";
        string p = "ab*a*c*a";
        Solution ss;
        cout << ss.isMatch(s,p) <<endl;
    }

  • 0
    W

    Solved!
    I didn't initialize the d array at first.
    So values in the array is non-deterministic and I happened to got right answer in my pc and happened to got wrong answer in OJ.


Log in to reply
 

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