码迷,mamicode.com
首页 > 其他好文 > 详细

括号匹配(二)

时间:2016-07-03 21:39:11      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

//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--];
}

括号匹配(二)

标签:

原文地址:http://www.cnblogs.com/guxuanqing/p/5638610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!