VALID PARENTHESES


  • 0
    S

    This solution is easy but lot of corner case. we will use stack to see what is left and if we need to push it or not.

    1. if input is valid like start with (, [ , { bracket then we push it to stack.
    2. if input is ending bracket }.],) then we need to see if there is anything in stack or not.
      a. if nothing in stack then return false;
      b. if stack has some data then top of it should match with starting bracket.
    
    bool isValid(char* s) {
        char arr[10000];
        int i = 0;
        int k = 0;
        while(*s != '\0')
        {
                printf("%c\n",*s);
            switch(*s) {
                case '(' :
                case '[':
                case '{':
                arr[i++] = *s;
                    k++;
                        printf("i=%d  k=%d\n",i,k);
                    
                break;
                
                case ')' :
                if(i>0 && arr[i-1] != '(')
                return false;
                    else if(i>=0) {
                        
                        if(i > 0) i--; else return false;
                    }
                    break;
                
                case ']' :
                if(i > 0 && arr[i-1] !=  '[')
                return false;else if (i>=0){
                    if(i > 0) i--; else return false;
                }break;
                
                case '}' :
                if(i>0 && arr[i-1] != '{')
                               return false;
                    else if (i>=0){
                        if(i > 0) i--; else return false;
                        
                    }break;
                    default: continue;
               
            }
             s++;
                
            }
        printf("final i=%d  k=%d\n",i,k);
        if(i == 0 && k > 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.