X1504: Balanced Parentheses

Problem Description

Write a method balancedParens that checks if the given string has properly nested parentheses.

Method Signature:

public boolean balancedParens(String str)

Constraints

  • The string will not contain null values.
  • The input string may have any combination of the valid characters (parenthesis and other characters).
  • Use a stack to store the opening parenthesis "(".
  • The stack should only store opening parenthesis. For each closing parenthesis, pop from the stack and match.
  • When encountering a closing parenthesis ")", check if it the top of the stack has the corresponding opening parentheses. If it does, pop the stack. If not, return false.
  • Ignore all other characters.
  • At the end of the string, if the stack is empty, return true (indicating the parentheses are balanced). Otherwise, return false.

Documentation

Examples:

balancedParens("") -> true
balancedParens("()") -> true
balancedParens("(()(()))") -> true
balancedParens("(()()())") -> true
balancedParens(")(") -> false
balancedParens("print(x + y))") -> false

Your Answer:

Feedback

Your feedback will appear here when you check your answer.