通过观察,我们可以发现,括号匹配的字符串,左括号与右括号数目一定相等;且遇到右括号时,必定有与之相匹配的括号在之前最近出现过。这样,可以整理解决问题的思路如下:
假设有一串带括号的字符串,依次访问每一个字符,遇到左括号入栈;遇到右括号时,取栈顶元素,判断是否与该元素相等,若相等,则出栈;若不相等,则直接返回0;其余情况,皆不做任何操作,直接访问下一个字符,直到遇到‘\0’。
//seqstack.h
#pragma once
#include <stdlib.h>
#define SeqStackMaxSize 100
typedef char StackType;
typedef struct SeqStack
{
StackType data[SeqStackMaxSize];
size_t size;
}SeqStack;
void InitSeqStack(SeqStack* s);
void PushSeqStack(SeqStack* s, StackType elem);
void PopSeqStack(SeqStack* s);
int TopSeqStack(SeqStack* s, StackType* top);
int IsEmpty(SeqStack* s);
void Destroy(SeqStack* s);
//seqstack.c
#include <stdio.h>
#include "seqstack.h"
void InitSeqStack(SeqStack* s)
{
if(s == NULL)
return;
s->size = 0;
return;
}
void PushSeqStack(SeqStack* s, StackType elem)
{
if(s == NULL)
return;
s->data[s->size++] = elem;
return;
}
void PopSeqStack(SeqStack* s)
{
if(s == NULL)
return;
if(s->size == 0)
return;
s->size--;
return;
}
int TopSeqStack(SeqStack* s, StackType* top)
{
if(s == NULL)
return 0;
if(s->size == 0)
return 0;
*top = s->data[s->size-1];
return 1;
}
int IsEmpty(SeqStack* s)
{
if(s == NULL)
return 1;
if(s->size == 0)
return 1;
else
return 0;
}
void Destroy(SeqStack* s)
{
if(s == NULL)
return;
s->size = 0;
return;
}
#include <stdio.h>
#include "seqstack.h"
int MatchBrackets(char* buf, SeqStack* s)
{
if(buf == NULL)
return 1;
char* tmp = buf;
while((*tmp) != '\0')
{
switch(*tmp)
{
case '{':
case '(':
case '[':
{
PushSeqStack(s, *tmp);
tmp++;
break;
}
case '}':
case ')':
case ']':
{
char top = '0';
TopSeqStack(s, &top);
if((top == '{' && *tmp == '}') || (top == '(' && *tmp == ')') || (top == '[' && *tmp == ']'))
{
PopSeqStack(s);
tmp++;
}
else
return 0;
break;
}
default:
tmp++;
break;
}
}
if(IsEmpty(s))
return 1;
else
return 0;
}
int main()
{
SeqStack s;
SeqStack s1;
SeqStack s2;
InitSeqStack(&s);
InitSeqStack(&s1);
InitSeqStack(&s2);
char* msg = "(()))abc{[]}";
char* msg1 = "(()()abc{[]}";
char* msg2 = "(())abc{[]()}";
int ret = MatchBrackets(msg, &s);
int ret1 = MatchBrackets(msg1, &s1);
int ret2 = MatchBrackets(msg2, &s2);
printf("%d\n", ret);
printf("%d\n", ret1);
printf("%d\n", ret2);
return 0;
}