大兴网站建设一条龙,青岛李沧区城乡建设局网站,wordpress毕业设计,石家庄外贸网站建设公司20. 有效的括号
给定一个只包括 ‘(’#xff0c;‘)’#xff0c;‘{’#xff0c;‘}’#xff0c;‘[’#xff0c;‘]’ 的字符串 s #xff0c;判断字符串是否有效。
有效字符串需满足#xff1a;
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭…20. 有效的括号
给定一个只包括 ‘(’‘)’‘{’‘}’‘[’‘]’ 的字符串 s 判断字符串是否有效。
有效字符串需满足
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。 class Solution {
public:bool isValid(string s) {if(s.length()%20){ stackchar st;for(int i0;is.length();i){char cs.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_mapchar, char pairs {{), (},{], [},{}, {}};stackchar 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
著作权归作者所有。商业转载请联系作者获得授权非商业转载请注明出处。