newcomer, runtime error,could you help me


  • 0
    X

    this is my code
    and i could not find the problem

    class Solution {
    public:
        bool isValid(string s) 
        {
            stack<char> stk;
            stk.push(s[0]);
    	for(int i = 1; i < s.size(); i++)
    	{
    	    char top = stk.top();
    	    if(top == '(' && s[i] == ')')
    	        stk.pop();
    	   else if(top == '[' && s[i] == ']')
    		stk.pop();
    	   else if(top == '{' && s[i] == '}')
    		stk.top();
    	   else
    		stk.push(s[i]);	
    	}
    	return stk.empty();
        }
    };
    

  • 0
    X

    @xiaohai1234 i have got the reason

    char top = stk.top();
    

    when stk is empty, the upper code will cause the runtime error.


Log in to reply
 

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