class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char ch : s.toCharArray()){
if(stack.isEmpty())
stack.add(ch);
else if(!stack.isEmpty()){
if(ch==']' && stack.peek()=='[')
stack.pop();
else if(ch=='}' && stack.peek()=='{')
stack.pop();
else if(ch==')' && stack.peek()=='(')
stack.pop();
else
stack.push(ch);
}
}
return stack.isEmpty();
}
}
Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more π€ && Happy Coding π
If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7
Top comments (2)
Do you need the if part of the else if? it seems redundant since it passed the outer IF part which is the same check.
We can use else instead of else-if. I wrote for the sake of my understanding (if that's what you are asking) π