?
1.直接使用库函数stack
#include<iostream>
#include<string>
#include<cstring>
#include<cstdlib>
#include<stack>
using namespace std;
#define MAXSIZE 20
void Matching(string s);
int main()
{
int n = 0;
cin >> n;
while (n > 0)
{
string s;
cin >> s;
Matching(s);
n--;
}
return 0;
}
void Matching(string s)
{
stack<char>st;
bool flag = 1;
unsigned int i = 0;
while (flag&&i < s.length())
{
switch (s[i])
{
case '(':
st.push(s[i]);
break;
case '[':
st.push(s[i]);
break;
case '{':
st.push(s[i]);
break;
case ')':
if (!st.empty() )
{
char ch=st.top();
if(ch=='(')
st.pop();
}
else flag = 0;
break;
case ']':
if (!st.empty() )
{
char ch=st.top();
if(ch=='[')
st.pop();
}
else flag = 0;
break;
case '}':
if (!st.empty() )
{
char ch=st.top();
if(ch=='{')
st.pop();
}
else flag = 0;
break;
}
i++;
}
if (st.empty() && flag)
{
cout << "Yes\n";
}
else { cout << "No\n"; }
}
2.自定义栈的数据结构
#include<iostream>//内存超限
#include<string>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
#define MAXSIZE 20
typedef struct
{
char *base;
char *top;
int stacksize;
}SqStack;
void InitStack(SqStack &S);
void Push(SqStack&S, char e);
void Pop(SqStack&S, char &e);
char GetTop(SqStack S);
bool StackEmpty(SqStack S);
void Matching(string s);
int main()
{
int n = 0;
cin >> n;
while (n > 0)
{
string s;
cin >> s;
Matching(s);
n--;
}
return 0;
}
void Matching(string s)
{
SqStack S;
InitStack(S);
bool flag = 1;
unsigned int i = 0;
while (flag&&i < s.length())
{
switch (s[i])
{
case '(':
Push(S, s[i]);
break;
case '[':
Push(S, s[i]);
break;
case '{':
Push(S, s[i]);
break;
case ')':
if (!StackEmpty(S) && GetTop(S) == '(')
{
Pop(S, s[i]);
}
else flag = 0;
break;
case ']':
if (!StackEmpty(S) && GetTop(S) == '[')
{
Pop(S, s[i]);
}
else flag = 0;
break;
case '}':
if (!StackEmpty(S) && GetTop(S) == '{')
{
Pop(S, s[i]);
}
else flag = 0;
break;
}
i++;
}
if (StackEmpty(S) && flag)
{
cout << "Yes\n";
}
else { cout << "No\n"; }
}
void InitStack(SqStack &S)
{
S.base = new char[MAXSIZE];
S.top = S.base;
S.stacksize = MAXSIZE;
}
void Push(SqStack&S, char e)
{
if (S.top - S.base == S.stacksize)return;
*S.top++ = e;
}
void Pop(SqStack&S, char &e)
{
if (S.top == S.base)return;
e = *--S.top;
}
char GetTop(SqStack S)
{
if (S.top != S.base)
return *(S.top - 1);
return -1;
}
bool StackEmpty(SqStack S)
{
if (S.top == S.base)
return true;
return false;
}
|