题目描述:
思路:遍历字符串所有元素,若为左括号,则入栈,如果为右括号,则直接获取栈顶元素,看是否匹配。
typedef char DataType;
typedef struct stack{
DataType *array;
int capacity;
int top;
}stack;
//栈的初始化
void stackInit(struct stack *ps,int capacity)
{
assert(ps);
ps->array=(DataType*)malloc(sizeof(DataType)*capacity);
if(NULL==ps->array)
{
// assert(0);
return ;
}
ps->capacity=capacity;
ps->top=0;
}
//销毁
void stackDestory(struct stack *ps)
{
assert(ps);
if(ps->array)
{
free(ps->array);
ps->capacity=0;
ps->top=0;
}
}
//检查容量
void checkCapacity(struct stack *ps)
{
assert(ps);
int newCapacity=0;
if(ps->top==ps->capacity)
{
newCapacity=(ps->capacity<<1);
DataType *temp=(DataType *)malloc(sizeof(DataType)*newCapacity);
if(NULL==temp)
{
assert(0);
//return ;
}
memcpy(temp,ps->array,sizeof(DataType)*ps->capacity);
free(ps->array);
ps->array=temp;
ps->capacity=newCapacity;
}
}
//入栈
void stackPush(struct stack *ps,char data)
{
checkCapacity(ps);
ps->array[ps->top]=data;
ps->top++;
}
bool stackEmpty(struct stack*ps)
{
assert(ps);
return ps->top==0;
}
//出栈
void stackPop(struct stack* ps)
{
if(stackEmpty(ps))
{
return ;
}
assert(ps);
ps->top--;
}
//获取栈顶元素
char stackTop(struct stack* ps)
{
return ps->array[ps->top-1];
}
bool isValid(char * s){
bool flag=true;
stack mystack;
stackInit(&mystack,10000);
int size=strlen(s);
for(int i=0;i<size;i++)
{
if((s[i]=='(')|| (s[i]=='[')||(s[i]=='{')) //若为左括号,则入栈
{
stackPush(&mystack,s[i]);
}
else
{
if(stackEmpty(&mystack)) //若数据中只有右括号,则当前栈为空,不能直接获取栈顶元素,要先判断栈是否为空
{
flag=false;
break;
}
char stackTopElem=stackTop(&mystack);
if(!((stackTopElem=='('&&s[i]==')')||(stackTopElem=='['&&s[i]==']')||(stackTopElem=='{'&&s[i]=='}')))
{
flag=false;
break;
}
stackPop(&mystack);
}
}
if(!stackEmpty(&mystack)) //若循环结束后栈不为空,则说明括号不匹配
{
flag=false;
}
stackDestory(&mystack);
return flag;
}