C solution use stack for Valid Parentheses


  • 0
    R

    i use a stack to save bracket whick have not par.....

    typedef struct{
        int isLR;
        int isPar;
    }bracket_obj;
    bool isValid(char* s) {
      	int i,len;
    	char stack[10000];
    	int index = 0;
        bracket_obj bra[126];
        i = 0;
        
        bra[40].isLR = 0;    bra[40].isPar = 1;
        bra[41].isLR = 1;    bra[41].isPar = 2;
        
        bra[91].isLR = 0;    bra[91].isPar = 3;
        bra[93].isLR = 1;    bra[93].isPar = 4;
        
        bra[123].isLR = 0;    bra[123].isPar = 6;
        bra[125].isLR = 1;    bra[125].isPar = 7;
        
        len = strlen(s);
    	if(len %2)return false;
    	while(s[i] != '\0')
    	{
            if((len-i) < index)return false;
    		if(index)
    		{
    		    //if ((s[i] == ')' && stack[index-1] == '(')||(s[i] == '}' && stack[index-1] == '{')||(s[i] == ']' && stack[index-1] == '['))
    			if((bra[s[i]].isPar - bra[stack[index-1]].isPar) == 1)
                {
    				index--;
    				i++;
    			}
    			else
    			{
                    if(bra[s[i]].isLR )return false;
    				stack[index++] = s[i++];
                    
    			}
    		}
    		else
    		{
                if(bra[s[i]].isLR )return false;
    			stack[index++] = s[i++];
    			continue;
    		}
    	}
    
    	if(index)return 0;
    	else return 1;
    }
    

Log in to reply
 

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