-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparenthesis.cpp
More file actions
28 lines (25 loc) · 845 Bytes
/
parenthesis.cpp
File metadata and controls
28 lines (25 loc) · 845 Bytes
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
class Solution {
public:
bool isValid(string s) {
stack<char> t; // stack for storing opening parentheses
int i; // variable i to travel
for(auto i:s) // travel into whole string
{
// if any opening parentheses, push into stack
if(i == '(' || i =='{' || i == '[')
{
t.push(i);
}
else
{
// check condition for false
if(t.empty() || (t.top() == '(' && i != ')') || (t.top() == '{' && i != '}') || (t.top() == '[' && i != ']'))
{
return false;
}
t.pop(); // else pop from stack
}
}
return t.empty(); // if stack is empty then it is valid, otherwise no
}
};