Valid Parentheses in Java: Explanation & Practice
Check if parentheses string is valid
Problem summary
Given a string containing just '(', ')', '{', '}', '[', ']', determine if the input string is valid. Use stack!
Starter code
public class Main {
public static void main(String[] args) {
String s = "([{}])";
// Push opening brackets onto stack
// For closing brackets, check if matches top
// Stack should be empty at end
// Print: Is valid: true
}
}Expected output and test cases
- ([{}])
Is valid: true
- ([)]
Is valid: false
Is valid: true
Hints
- Push opening brackets onto stack
- For closing bracket, pop and check if it matches
- If stack empty when trying to pop, invalid
- After processing, stack should be empty
Related Data Structures & Algorithms exercises
- Practice Longest Consecutive Sequence in Java
- Practice Valid Anagram in Java
- Practice Next Greater Element in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler