Why this code is not giving answer properly??


  • 0
    S

    bool isValid(string s) {

        stack <char> p;
        int n=s.length();
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(' || s[i]=='{' || s[i]=='[')
            p.push(s[i]);
            else
            {
                if(p.empty())
                return false;
                if(s[i]!=p.top())
                return false;
                p.pop();
            }
        }
        if(p.empty())
        return true;
        else
        return false;
    }

  • 0
    X

    if(s[i]!=p.top())
    this line of you code should be replaced by :
    boolean isMatched(char ele, char top)
    {
    if (top == '(') return ele == ')';
    if (top == '{') return ele == '}';
    if (top == '[') return ele == ']';
    return false;
    }

    Also, at last just return p.empty();


Log in to reply
 

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