forked from PRAteek-singHWY/hackoctoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_paranthesis_problem.cpp
More file actions
40 lines (30 loc) · 1.27 KB
/
valid_paranthesis_problem.cpp
File metadata and controls
40 lines (30 loc) · 1.27 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
// 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.
// Every close bracket has a corresponding open bracket of the same type.
#include<bits/stdc++.h>
using namespace std;
bool isValid(string s) {
// approach - using stack
int n = s.size();
stack<char> st;
if(n == 1) return false;
for(int i = 0 ; i<n ; i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
st.push(s[i]);
}
else if((s[i] == ')' && st.empty()) || (s[i] == ']' && st.empty()) || (s[i] == '}' && st.empty())) return false;
else if((s[i] == ')' && st.top() != '(') || (s[i] == ']' && st.top() != '[') || (s[i] == '}' && st.top() != '{')) return false;
else if((s[i] == ')' && st.top() == '(') || (s[i] == ']' && st.top() == '[') || (s[i] == '}' && st.top() == '{')){
st.pop();
}
}
if(st.empty()) return true;
return false;
}
int main(){
string s = "()()";
cout<<isValid(s)<<endl;
return 0;
}