-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.txt
29 lines (26 loc) · 872 Bytes
/
20.txt
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
Valid Parenthesis
Given a string with different parenthesis '( ) [ ] { }'
check whether the string is valid or not i.e each opening bracket has a closing bracket
We can use a stack to store the opening bracket and according to curr character we can make changes
We use stack so that to match the closing bracket with the most recent opening bracket (i.e. LIFO)
bool isValid(string s) {
stack<char> st;
for(auto c:s){
if(c=='(' || c=='[' || c=='{'){
st.push(c);
}
if(c==')' && (st.empty() || st.top()!='(')){
return false;
}
if(c==']' && (st.empty() || st.top()!='[')){
return false;
}
if(c=='}' && (st.empty() || st.top()!='{')){
return false;
}
if(c==')' || c==']' || c=='}'){
st.pop();
}
}
return st.empty();
}