采用顺序栈判断表达式中的括号是否正确配对
【习题描述】
习题描述:
h. 假设表达式中允许包含3中括号:圆括号、方括号和大括号。设计一个算法采用顺序栈判断表达式中的括号是否正确配对。
用例1:
假设输入为:
{1*[3*2+(2-1)]}
则输出为:
匹配正确!
用例2:
假设输入为:
则输出为:
{ 匹配错误
用例3:
假设输入为:
{1*[3*2+(2-1)}]
则输出为:
} 匹配错误
用例4:
假设输入为:
(1*(3-(3*[3%[4=[t }5}7-}i9]73]24]5-)6)+)6*)5%{6*{3^{2!!(
则输出为:
} 匹配错误
用例5:
假设输入为:
) ] } { ] (
则输出为:
) 匹配错误
/*课后习题1.8-h
h. 假设表达式中允许包含3中括号:圆括号、方括号和大括号。
设计一个算法采用顺序栈判断表达式中的括号是否正确配对。
void Bracketmatch(const char* c)
*/
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class stack {
private:
int maxsize;
int top;
char* st;
public:
stack(int size)
{
maxsize = size;
top = -1;
st = new char[maxsize];
}
void push(char item)
{
st[++top] = item;
}
char top1()
{
return st[top];
}
void pop()
{
top--;
}
bool empty()
{
return top == -1;
}
};
/*
TODO:计一个算法采用顺序栈判断表达式c中的括号是否正确配对。
输出:1. 遍历表达式c过程中,匹配错误 cout << c[i] << " 匹配错误" << endl;
2. 遍历之后,栈为空,则匹配正确,cout << "匹配正确!" << endl;
若不为空,则 cout << s1.top1() << " 匹配错误" << endl;
*/
void Bracketmatch(const char* c) //括号匹配
{
stack s1(strlen(c));
bool flag1= true,flag2= false;
for (int i = 0; i < strlen(c); ++i) {
if (i< strlen(c)-1&&c[i]=='/'&&c[i+1]=='/'){
flag2= true;
for (int j = i; j < strlen(c)-1; ++j) {
if (c[j]=='/'&&c[j+1]=='n'){
i=j+1;
flag2= false;
}
}
}
if (flag2){
cout << "匹配正确!1" << endl;
break;
}
if (i< strlen(c)-1&&c[i]=='/'&&c[i+1]=='*'){
for (int j = i; j < strlen(c)-1; ++j) {
if (c[j]=='*'&&c[j+1]=='/'){
i=j+1;
}
}
}
if (c[i]=='{'&&s1.top1()!='['&&s1.top1()!='('||c[i]=='['&&s1.top1()!='('||c[i]=='('){
s1.push(c[i]);
}
if (c[i]==')'||c[i]==']'||c[i]=='}'){
if (c[i]==')'&&s1.top1()=='('||c[i]==']'&&s1.top1()=='['||c[i]=='}'&&s1.top1()=='{'){
s1.pop();
} else{
cout << c[i] << " 匹配错误" << endl;
flag1= false;
break;
}
}
}
if (flag1&&!flag2){
if (s1.empty()){
cout << "匹配正确!2" << endl;
} else{
cout << s1.top1() << " 匹配错误" << endl;
}
}
}
int main()
{
string s;
getline(cin, s);
Bracketmatch(s.c_str());
return 0;
}