括号匹配
当需要检测成对出现但又互不相邻的事物时可以使用栈“后进先出”的特性
栈非常适合于需要“就近匹配”的场合
- 思路
- 从第一个字符开始扫描
- 当遇见普通字符时忽略
- 当遇见左符号时压入栈中
- 当遇见右符号时从栈中弹出栈顶符号,并进行匹配
- 匹配成功:继续读入下一个字符
- 匹配失败:立即停止,并报错
- 结束:
- 成功: 所有字符扫描完毕,且栈为空
- 失败:匹配失败或所有字符扫描完毕但栈非空
代码实现
bool isLeft(char a) //判断是否是左括号
{
return a == '(';
}
bool isRight(char a)//判断是否是右括号
{
return a == ')';
}
void printError(int index)//打印错误符号,让*指向错误匹配位置
{
for (int i=0;i<index;i++)
{
cout << " ";
}
cout << "*";
}
/*------------------------------------------------------------*/
void match(const char* str)
{
string stmp = str;
stack<char> mysta;
int count = 0;
bool flag = true;
for (string::iterator it=stmp.begin();it!=stmp.end();it++)
{
if (isLeft(*it))//如果是左括号
{
//入栈(
mysta.push(*it);
}
if (isRight(*it))//如果是右括号
{
if (mysta.size()>0)
{
if (isLeft(mysta.top()))
{
mysta.pop();//出栈
}
else
{
cout << endl;
cout << "匹配失败" << endl;
cout << str << endl;
printError(count);
flag = false;
}
}
}
}
count++;
cout << endl;
if (flag)
{
cout << "匹配成功" << endl;
}
cout << endl;
}
//测试----
void main()
{
match("1+2+6(dsf)dfs)flp(sdfs)");
return;
}