-
Notifications
You must be signed in to change notification settings - Fork 0
/
validParenthesis.cpp
56 lines (46 loc) · 1.33 KB
/
validParenthesis.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// An input string is valid if:
// 1. Open brackets must be closed by the same type of brackets.
// 2. Open brackets must be closed in the correct order.
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Solution{
public:
bool isValid(string s){
stack<char> stack1;
if(s.size()%2!=0){
return false;
}
for(int i=0; i<s.size(); i++){
if(s[i]=='(' || s[i]=='{' || s[i]=='['){
stack1.push(s[i]);
}
else
{
if(!stack1.empty()&&((s[i]==')'&&stack1.top()=='(')||(s[i]=='}'&&stack1.top()=='{')||(s[i]==']'&&stack1.top()=='[')))
{
stack1.pop();
}
else
{
return false;
}
}
}
if(stack1.empty()){
return true;
}
else{
return false;
}
}
};
int main(){
string str;
cout<<"Enter the string";
cin>>str;
Solution sol;
sol.isValid(str);
}