#include<stdio.h>
#define true 1
#define false 0
#define maxsize 100
typedef int status;
status match(char exp[], int n)
{
if(n<0)
{
printf("匹配失败!");
return false;
}
char stack[maxsize]; int top = -1;
for (int i=0; i<n; i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
stack[++top] = exp[i];
else if(exp[i] == ')')
{
if(stack[top] == '(')
top--;
else
{
printf("匹配失败!");
return false;
}
}
else if(exp[i] == '}')
{
if(stack[top] == '{')
top--;
else
{
printf("匹配失败!");
return false;
}
}
else if(exp[i] == ']')
{
if(stack[top] == '[')
top--;
else
{
printf("匹配失败!");
return false;
}
}
}
if(top == -1)
{
printf("匹配成功!");
return true;
}
else
{
printf("匹配失败!");
return false;
}
}
void main()
{
char exp[maxsize];
int n, i, x;
printf("请输入表达式的长度n:\n");
scanf("%d", &n);
getchar();
if(n>0)
{
printf("请逐个输入表达式中的字符:\n");
for(i=0; i<n; i++)
{
x = getchar();
exp[i] = x;
printf("exp[%d]=%c\n", i, exp[i]);
}
}
match(exp, n);
}
class Solution {
public:
bool isValid(string s) {
if(s.size()==0) return true;
stack<char>st;
for(int i=0;i<s.size();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{') st.push(s[i]);
else if(st.empty()) return false;
else
{
if(s[i]==')'&&st.top()=='(') st.pop();
else if(s[i]==']'&&st.top()=='[') st.pop();
else if(s[i]=='}'&&st.top()=='{') st.pop();
else return false;
}
}
if(!st.empty()) return false;
return true;
}
};