链接:https://www.nowcoder.com/questionTerminal/1490015bafce40e1920fd8a02a71ecaa?answerType=1&f=discussion
来源:牛客网
判断由"()[]{}"6种括号组成的字符串是否合法

  1. 所有括号必须闭合
  2. 左括号必须在正确的位置闭合
    输入描述:
    由6种符号组成的字符串
    输出描述:
    合法则输出"true",不合法输出"false"
    示例1
    输入
    (]
    输出
    false
    示例2
    输入
    {[][()()]}
    输出
    true
    示例3
    输入
    {([)]}
    输出
    false

c++栈解法
#include<bits/stdc++.h>

using namespace std;

int main() {
string str;
cin >> str;
stack<char>st;
map<char,char>m;
m[')']='(';
m[']']='[';
m['}']='{';
bool flag=true;
for(int i = 0; i < str.size();i++){
if(st.empty()){
st.push(str[i]);continue;
}
char first=st.top();
if(first ==')' || first==']' || first=='}'){
flag = false;break;
}
else if(m[str[i]] != first){
st.push(str[i]);
}
else{
st.pop();
}
}
if(!st.empty())flag=false;
if(flag)cout<<"true";
else cout<<"false";
}</char>