Why my cpp get a result of runtime error?


  • 0
    S
    public:
        bool isValid(string s) {
            stack<char> result;
    		for(int i=0; i<s.length(); i++)
    		{
    			if(s[i]==')' || s[i]==']' || s[i]=='}')
    			{
    				if(result.top()==s[i]-1 || result.top()==s[i]-2)
    					result.pop();
    				else
    					return false;
    			}
    			else
    				result.push(s[i]);
    		}
    		if(!result.empty()) return false;
    
    		return true;	
       
    };
    
    **Can someone explain to me?Thx very much!!**

  • 0
    H

    The problem is you cannot access the top of a stack when it is empty, be careful next time : )


  • 0
    S

    @H41 Thank you for your help! It was most careless of me!


Log in to reply
 

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