Valid Parentheses Solutions in C++
Number 20
Difficulty Easy
Acceptance 39.0%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/valid-parentheses/// Author : Hao Chen// Date : 2014-06-30#include <iostream>#include <string>#include <stack>using namespace std;bool isValid(string s) {stack<char> st;for(auto ch : s) {if (ch=='{' || ch =='[' || ch=='(' ) {st.push(ch);}else if (ch=='}' || ch ==']' || ch == ')' ){if (st.empty()) return false;char sch = st.top();if ( (sch=='{' && ch =='}') || (sch=='[' && ch==']') || (sch=='(' && ch==')' ) ){st.pop();}else {return false;}}else{return false;}}return st.empty();}int main(int argc, char**argv){string s = "{{}{[]()}}";if (argc>1){s = argv[1];}cout << "str = \"" << (s) << "\"" << endl;cout << isValid(s) << endl;}
C++ solution by pezy/LeetCode
#include <string>#include <stack>using std::string; using std::stack;class Solution {public:bool isValid(string s) {stack<char> stk;for (auto c : s)if (!stk.empty() && ((c == ')' && stk.top() == '(') || (c == '}' && stk.top() == '{') || (c == ']' && stk.top() == '['))) stk.pop();else stk.push(c);return stk.empty();}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/valid-parentheses/description//// Author : liuyubobobo/// Time : 2017-11-17#include <iostream>#include <stack>#include <cassert>using namespace std;// Using Stack// Time Complexity: O(n)// Space Complexity: O(n)class Solution {public:bool isValid(string s) {stack<char> stack;for( int i = 0 ; i < s.size() ; i ++ )if( s[i] == '(' || s[i] == '{' || s[i] == '[')stack.push(s[i]);else{if( stack.size() == 0 )return false;char c = stack.top();stack.pop();char match;if( s[i] == ')' )match = '(';else if( s[i] == ']' )match = '[';else{assert( s[i] == '}' );match = '{';}if(c != match)return false;}if( stack.size() != 0 )return false;return true;}};void printBool(bool res){cout << (res ? "True" : "False") << endl;}int main() {printBool(Solution().isValid("()"));printBool(Solution().isValid("()[]{}"));printBool(Solution().isValid("(]"));printBool(Solution().isValid("([)]"));return 0;}