20. 有效的括号
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
class Solution {
public:bool isValid(string s) {if(s.length()%2==0){ stack<char> st;for(int i=0;i<s.length();i++){char c=s.at(i);if(c=='('||c=='['||c=='{'){st.push(c);}else if(c==')'){if(!st.empty()&&st.top()=='('){st.pop();}else{return false;}}else if(c=='}'){if(!st.empty()&&st.top()=='{'){st.pop();}else{return false;}}else{if(!st.empty()&&st.top()=='['){st.pop();}else{return false;}}}return st.empty();}return false;}
};
Leecode官方代码:
class Solution {
public:bool isValid(string s) {int n = s.size();if (n % 2 == 1) {return false;}unordered_map<char, char> pairs = {{')', '('},{']', '['},{'}', '{'}};stack<char> stk;for (char ch: s) {if (pairs.count(ch)) {if (stk.empty() || stk.top() != pairs[ch]) {return false;}stk.pop();}else {stk.push(ch);}}return stk.empty();}
};作者:力扣官方题解
链接:https://leetcode.cn/problems/valid-parentheses/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。