solution in c with stack


  • 0
    W

    bool isValid(char* s) {

    int k = strlen(s);
    
    char *stk;
    stk = (int *)malloc(sizeof(int) * (k+1));
    
    int top = 0;
    while (*s)
    {
    	if ((*s == '(') || (*s == '[') || (*s == '{'))
    	{
    		top++;
    		stk[top] = *s;
    
    	}
    
    
    
    	if (*s == ')')
    	{
    
    		if (stk[top] == '(')
    		{
    			stk[top] = 0;
    			top--;
    		}
    		else
    			return false;
    	}
    	if (*s == ']')
    	{
    
    		if (stk[top] == '[')
    		{
    			stk[top] = 0;
    			top--;
    		}
    		else
    			return false;
    	}
    	if (*s == '}')
    	{
    
    		if (stk[top] == '{')
    		{
    			stk[top] = 0;
    			top--;
    		}
    		else
    			return false;
    	}
    
    	s++;
    }
    if (stk[top] == 0)
    	return true;
    else
    	return false;
    

    }


Log in to reply
 

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