括号匹配

来源:互联网 发布:圣思园java视频下载 编辑:程序博客网 时间:2024/05/21 11:37

栈的一个简单应用,检查字符串中的括号是否匹配。具体思路是扫描每个字符,遇到(,[,{则入栈,遇到),],}则检查栈顶元素,如果栈顶元素不是与之匹配的(或[或{则证明不匹配,可以设置标志位并提前退出。全部扫描完成后如果标志位被置位或者栈不为空,说明该表达式不匹配。

代码如下:

// bracketmatch.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <stack>#include <algorithm>#include <cstdlib>#include <string>using namespace std;bool checkBracketmatch(string words){int flag = 1; //匹配标志stack<char> S;for (int i = 0; i < words.size(); i++){if (words[i] == '(' || words[i] == '[' || words[i] == '{')S.push(words[i]);else{switch (words[i]){case ')':if (!S.empty()&&S.top() == '(')S.pop();elseflag = 0;break;case ']':if (!S.empty()&&S.top() == '[')S.pop();elseflag = 0;break;case '}':if (!S.empty()&&S.top() == '{')S.pop();elseflag = 0;break;default:break;}}if (flag == 0)return false;}if (flag == 0 || !S.empty())return false;return true;}int main(){string s;while (cin >> s){if (checkBracketmatch(s))cout << "Match!\n";elsecout << "Not match!\n";}system("pause");return 0;}



运行结果: