栈的应用——括号匹配
#include <iostream>
#include <stack>
using namespace std;
bool bracketMatch(string str){
stack<char> s;
for(char c:str){//遍历括号串
if(c == '(' || c == '[' || c == '{')
s.push(c);//扫到左括号就入栈
else{//扫到右括号
if( s.empty() )
return false;//栈空,右括号单身,匹配失败
char leftBracket = s.top();//用栈顶左括号与其进行匹配
s.pop();
if( (c == ')' && leftBracket != '(') ||
(c == ']' && leftBracket != '[') ||
(c == '}' && leftBracket != '{') )
return false;
}
}
return s.empty();//如果最后栈为空则说明匹配成功,栈空返回true
}
int main(){
string s1 = "((()))";
string s2 = "([{}])";
if(bracketMatch(s1))
cout << "s1 matched" << endl;
else
cout << "s1 not matched" << endl;
if(bracketMatch(s2))
cout << "s2 matched" << endl;
else
cout << "s2 not matched" << endl;
return 0;
}