有效的括号(利用栈解法)

  • 给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

Typedef char STDataType;
Typedef struct Stack{
  STDataType *_a;
  int _top = 0;
  int _capacity = 0;
 }Stack;
Stack st;

void StackInit(Stack* ps){
	assert(ps);
	ps->_a = NULL;
	ps->_top = 0;
	ps->_capacity = 0;
 }

void StackDestory(Stack* ps){
	assert(ps);
	free(ps->_a);
	ps->_a = NULL;
	ps->_top = 0;
	ps->_capacity = 0;
}

void StackPush(Stack* ps, STDataType x){
    assert(ps);
    if (ps->_top==ps->_capacity){
      int newcapacity = ps->_capacity==0 ? 4:2*(ps->_capacity);
      ps->_a = (STDataType*)realloc(ps->_a,newcapacity*sizeof(STDataType));
      //栈的增容,是给栈里面的数组开空间,一般用realloc动态开辟。
      assert(ps->_a);
      ps->_capacity = newcapacity;
     }
    ps->_a[ps->top] = x;
    ps->top++;
  }
  
void StackPop(Stack* ps){
	assert(ps&&ps->_top > 0);
	--(ps->_top);
 }

STDataType StackTop(Stack* ps){
	assert(ps&&ps->_top > 0);
	return  ps->_a[ps->_top-1];
 }
	
int StackEmpty(Stack* ps){
	assert(ps);
	if (ps->_top == 0){
		return 0;
    }
	else{
		return 1;
	}
}

int StackSize(Stack* ps){
	assert(ps);
	return ps->_top;
}
 
 bool isValid(char* s) {
  Stack st;
  StackInit(&st);
  
  while(*s){
    if(*s=='(' || *s=='[' || *s=='{'){
      StackPush(&st,*s);
    }
    else{
     if (StackEmpty(&st)==0){
       return false;
     }
     int top = StackTop(&st);
     if(*s==')'{
       if(top=='('){
          StackPop(&st);
       }
       else{
          StackDestory(&st);
          return false;
       }
     }
         
     if(*s==']'{
       if(top=='['){
          StackPop(&st);
       }
       else{
          StackDestory(&st);
          return false;
       }
     }
         
     if(*s=='}'{
       if(top=='{'){
          StackPop(&st);
       }
       else{
          StackDestory(&st);
          return false;
       }
     }
    }
    s++;
  }
if (StackEmpty(&st)==0){
   return true;
 }
  return false;
}

猜你喜欢

转载自blog.csdn.net/Darling_sheeps/article/details/86147995
今日推荐