-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2_validParenthesis.cpp
More file actions
42 lines (34 loc) · 1.38 KB
/
q2_validParenthesis.cpp
File metadata and controls
42 lines (34 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stack>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> st; //taking stack for keep tracking the order of the brackets..
// auto = string::iterator
for(auto i:s) //iterate over each and every elements
{
// simultaneous push and check
// if opening bracket, straightaway push
if(i=='(' or i=='{' or i=='[') st.push(i); //if current element of the string will be opening bracket then we will just simply push it into the stack
// for closing brackets, check if those in stack matches those in string
// first CLOSING should match the first OPENING
else
{
if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or (st.top()=='[' and i!=']')) return false;
st.pop(); //if control reaches to that line, it means we have got the right pair of brackets, so just pop it.
}
}
return st.empty(); //at last, it may possible that we left something into the stack unpair so return checking stack is empty or not..
}
};
int main()
{
// q2 valid parenthesis
Solution s2;
string s = "([)]";
bool result = s2.isValid(s);
cout << "result"<< result << endl;
return 0;
}