栈的应用——就近匹配问题

就近匹配是栈最典型的应用,最常见的就是括号匹配。

思路:遇到一个左括号就压栈;遇到一个右括号就先看栈是否为空,不为空就弹栈,为空就输出不匹配;遍历一遍后检查下栈是否为空,若不为空,输出不匹配。

#include <iostream>
#include <stack>
#include <string>

using namespace std;

typedef struct NODE {
	char data;
	int index;
}Node;

int IsLeft(char c) {
	return c == '(';
}

int IsRight(char c) {
	return c == ')';
}

void ShowError(string str, int index) {
	cout << str << endl;
	for (int i = 0; i < index; i++)
		cout << ' ';
	cout << 'A' << endl;
}

int main()
{
	string str = "(1+2)(((1-3)";
	int index = 0;
	stack<Node> s;
	Node node;
	for (int i = 0; i < str.size(); i++) {
		if (IsLeft(str[i])) {
			node.data = str[i];
			node.index = i;
			s.push(node);
		}
		if (IsRight(str[i])) {
			if (s.size() > 0) {
				Node temp = s.top();
				if (IsLeft(temp.data))
					s.pop();
				}
			else {
				ShowError(str, i);
			}
		}
	}
	while (s.size() > 0) {
		node = s.top();
		ShowError(str, node.index);
		s.pop();
	}
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值