Leetcode 20. Valid Parentheses | | Leetcode 20. Valid Parentheses 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution Version 1 1234567891011121314151617181920class Solution {public: bool isValid(string s) { stack<char> st; for(char ch : s) { if(st.empty()) { st.push(ch); } else { if((ch == ')' && st.top() == '(') || (ch == ']' && st.top() == '[') || (ch == '}' && st.top() == '{')) { st.pop(); } else { st.push(ch); } } } return st.empty(); }}; Version 2 1234567891011121314151617181920212223class Solution {public: bool isValid(string s) { stack<char> st; for(char ch : s) { if(st.empty()) { st.push(ch); } else { if((ch == ')' && st.top() != '(') || (ch == ']' && st.top() != '[') || (ch == '}' && st.top() != '{')) { return false; } else if(ch == ')' || ch == ']' || ch == '}'){ st.pop(); } else { st.push(ch); } } } return st.empty(); }}; Reference https://leetcode.com/problems/valid-parentheses/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏