算法描述
算式括号匹配:
括号都是成对出现,一左一右
可以利用栈,将所有左边的括号,按照出现的顺序压入栈中,那么最后一个左括号应该对应第一个右括号,
因此,只需比较栈中左括号与接下来出现的右括号是否匹配即可,(注意,右括号不入栈,只有左括号入栈)
括号匹配可能出现以下四种情况:
1)左右括号数量相等且都匹配
2)左括号多,表现为存储括号的栈不为空
3)右括号多,表现为检测到右括号但存储左括号的栈为空
4)左右括号数量相等,出现不匹配
C++代码
kuohaopipei.h 文件代码
#ifndef KUOHAOPIPEI_H_
#define KUOHAOPIPEI_H_
const int MaxSize = 1000;
template<class T>
class SeqStack
{
public:
SeqStack(){top = 0;length = 0;};
void Push(T x);
T Pop();
T GetTop();
int GetLength();
private:
int top;
int length;
T data[MaxSize];
};
#endif
template<class T>
void SeqStack<T>::Push(T x)
{
if(length > MaxSize)throw"上溢";
top = top + 1;
data[top] = x;
length++;
}
template<class T>
T SeqStack<T>::Pop()
{
if(top < 0)throw"下溢";
T x;
x = data[top];
top --;
length --;
return x;
}
template<class T>
T SeqStack<T>::GetTop()
{
if(top < 0)throw"下溢";
T x;
x = data[top];
return x;
}
template<class T>
int SeqStack<T>::GetLength()
{
return length;
}
kuohaopipei.cpp文件
#include<iostream>
#include"kuohaopipei.h"
#include<string>
using namespace std;
int Match(char ch1,char ch2)
{int t = 0;
if(ch1 == '(' && ch2 == ')')
{t = 1;}
if(ch1 == '[' && ch2 == ']')
{t = 1;}
if(ch1 == '{' && ch2 == '}')
{t = 1;}
return t;
}
void main()
{
SeqStack<char> str;
string s1;
int sign = 0;
char p;
cout<<"请输入算式:"<<endl;
getline(cin,s1);
for(int i = 0; i < s1.size();i++)
{
if(s1[i] == '('||s1[i] == '['||s1[i] == '{')
str.Push(s1[i]);//左括号入栈
else if(s1[i] == ')'||s1[i] == ']'||s1[i] == '}')
{
if(str.GetLength() == 0)
{
sign = 0;
cout<<"右括号多余!\n";//3)右括号多余
}
else
{
p = str.Pop();//检测到右括号,让左括号出栈,并比较两个是否匹配
if(Match(p,s1[i]))
sign = 1;//1)只有当括号匹配时,sign=1
else if(!Match(p,s1[i]))
sign = 0;//4)不匹配时,sign =0,匹配错误标签
}
}
}//end for循环
if(str.GetLength() != 0)
{
sign = 0;
cout<<"左括号多余!\n";//2)左括号多余
}
cout<<"算式为:"<<s1<<endl;
if(sign) cout<<"圆括号匹配正确!"<<endl;
else cout<<"圆括号匹配错误!"<<endl;
system("pause");
}