-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path29_Valid Parentheses
40 lines (36 loc) · 1.06 KB
/
29_Valid Parentheses
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
/*
Remember while solving:
1)Convey your thoughts clearly to the interviewer
2)Maintain topmost code quality
3)Discuss testcases while solving
4)Evolve from brute->Better->optimal
*/
//Use a stack
//link to the problem:https://leetcode.com/problems/valid-parentheses/
//DSA sheet by Arsh Goyal: Problem 29
class Solution {
public boolean isValid(String s) {
int length=s.length();
Stack<Character> st=new Stack<Character>();
for(int i=0;i<length;i++){
char bracket=s.charAt(i);
if(bracket=='(' || bracket=='{' || bracket=='['){
st.push(bracket);
}
else{
if(st.empty())
return false;
else{
char ch=st.peek();
st.pop();
if((bracket==')' && ch!='(') || (bracket=='}' && ch!='{') || (bracket==']' && ch!='['))
return false;
}
}
}
if(st.empty())
return true;
else
return false;
}
}