就近匹配是栈最典型的应用,最常见的就是括号匹配。
思路:遇到一个左括号就压栈;遇到一个右括号就先看栈是否为空,不为空就弹栈,为空就输出不匹配;遍历一遍后检查下栈是否为空,若不为空,输出不匹配。
#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;
}