题目:给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>
#include<stack>
using namespace std;unordered_map<char, char> up = {{'(' , ')'},{'{' , '}'},{'[' , ']'},
};class Solution
{
public:bool isValid(string s){stack<char> st;for (char c : s){if (up.count(c)) //判断c是否是up的键,是的话就压栈{st.push(c); }else if(st.empty() || up[st.top()] != c){return false;}else //up[st.top()] == c{st.pop();}}return st.empty();}
};int main()
{Solution a;cout <<"a.isPalindrome : " << a.isValid("{([])}") << endl;return 0;
}