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

  1. Push opening brackets onto stack
  2. For closing bracket, pop and check if it matches
  3. If stack empty when trying to pop, invalid
  4. After processing, stack should be empty

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler