Description
Implement the following function that decides if a list of brackets match.
bool brackets(string s);
/*
The input s is a list of brackets, including {,},(,),[,], and possibly blanks.
The function returns true if the brackets match, otherwise false.
*/
符号匹配问题,用栈来解决。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool isMatch(char a,char b) //判断是否匹配
{
<span style="white-space:pre"> </span>if((a=='{' && b=='}') || (a=='[' && b==']') || (a=='(' && b==')'))
<span style="white-space:pre"> </span>return true;
<span style="white-space:pre"> </span>else return false;
}
bool brackets(string s) {
<span style="white-space:pre"> </span>stack<char> a;
<span style="white-space:pre"> </span>for (int i = 0; i < s.size(); ++i) {
<span style="white-space:pre"> </span>char b = s[i];
<span style="white-space:pre"> </span>if (b == ' ') continue; //无视空格
<span style="white-space:pre"> </span>if (!a.empty() && isMatch(a.top(), b)) //如果匹配
<span style="white-space:pre"> </span>a.pop();
<span style="white-space:pre"> </span>else a.push(b);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if (a.empty()) return 1;
<span style="white-space:pre"> </span>else return 0;
}