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;
}
括号匹配算法解析
本文介绍了一种使用栈实现的括号匹配算法,该算法能够判断由多种括号组成的字符串是否正确配对。通过逐个检查输入字符串中的字符并利用栈进行辅助处理,实现了有效的括号匹配验证。
503

被折叠的 条评论
为什么被折叠?



