Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Programming Challenge: Valid Parentheses

4. Bracket Validation

Problem Statement: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Function Signature:

public boolean isValid(String s);

Examples:

  • Input: "()[]{}"
    Output: true
  • Input: "(]"
    Output: false

Solution Code

import java.util.Stack;

public class ParenthesesValidator {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) return false;
                char top = stack.pop();
                if (!((c == ')' && top == '(') || 
                      (c == '}' && top == '{') || 
                      (c == ']' && top == '['))) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

Complexity Analysis

Approach Time Complexity Space Complexity
Stack O(n) O(n)