括号匹配(二)

//C v0.01 不知题意,正在理解,正在(一)上修改。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACK_SIZE 10000
typedef struct STACK{
  char stack[STACK_SIZE];
  int pointer;
}STSTACK;
STSTACK stack;

void push(char ch);
char pop();

int main(int argc, char *argv[])
{
  int num;
  int i;
  char buf[STACK_SIZE]={0};
  int sum = 0;
  scanf("%d",&num);
  getchar();

  for(i = 0;i < num;i++){
      memset(stack.stack, 0x00, STACK_SIZE);
      stack.pointer = -1;
      scanf("%s", buf);
      getchar();
      int len = strlen(buf);
      //printf("%d\n",len);
      int j;
      int flag=1;
      for(j = 0;j < len;j++){
          char tmp;
          if(buf[j] == '[' || buf[j] == '('){
              push(buf[j]);

            }else if (buf[j] == ']') {
              if(stack.pointer == -1){
                  //--stack.pointer;
                  flag = 0;
                  push(buf[j]);
                  //++sum;
                  //printf("No\n");
                  //break;
                  continue;
                }
              tmp = pop();
              if(tmp != '['){
                  //push(tmp);
                  //printf("No\n");
                  flag = 0;
                  push(tmp);
                  push(buf[j]);
                  //break;
                  continue;
                }/*else if(tmp == '['){
                        continue;
                      }*/

            }else if (buf[j] == ')') {
              if(stack.pointer == -1){
                 // --stack.pointer;
                  flag = 0;
                  push(buf[j]);
                  //++sum;
                  //printf("No\n");
                  //break;
                  continue;
                }
              tmp = pop();
              if(tmp != '('){
                  //push(tmp);
                  //printf("No\n");
                  flag = 0;
                  push(tmp);
                  push(buf[j]);
                  //break;
                  continue;
                }/*else if(tmp == '('){
                        continue;
                      }*/
            }
        }


      if(stack.pointer == -1 && flag){
          //printf("Yes\n");
          printf("0\n");
        }else{
                //printf("No\n");
          printf("%d\n",stack.pointer+1);
            }

    }
  return 0;
}

void push(char ch){
  stack.stack[++stack.pointer] = ch;
}

char pop(){
  return stack.stack[stack.pointer--];
}

posted @ 2016-07-03 19:15  PKICA  阅读(306)  评论(0编辑  收藏  举报