###### tags: `leetcode` # Question 20. Valid Parentheses ### Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: - Open brackets must be closed by the same type of brackets. - Open brackets must be closed in the correct order. ### Solution: Stack ``` - include <stack> - initial - stack<char> mystack, mystack2; - mystack.size() - mystack.empty() - mystack.push(element) - mystack.top() - mystack.pop() - mystack.swap(mystack2) ``` ### AC code ```cpp= #include <stack> class Solution { public: bool isValid(string s) { stack<char> stack; for(int i = 0 ; i < s.length() ; i++){ if(s[i] == ')'){ if(!stack.empty() && stack.top() == '(') stack.pop(); else{ return false; } } else if(s[i] == ']'){ if(!stack.empty() && stack.top() == '[') stack.pop(); else{ return false; } } else if(s[i] == '}'){ if(!stack.empty() && stack.top() == '{') stack.pop(); else{ return false; } else stack.push(s[i]); } if(!stack.empty()) return false; else return true; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up