Balanced Parentheses in JavaThe balanced parentheses problem is one of the common programming problems that is also known as Balanced brackets. This problem is commonly asked by the interviewers where we have to validate whether the brackets in a given string are balanced on not. Characters such as "(", ")", "[", "]", "{", and "}" are considered brackets. A collection of parentheses is considered to be a matched pair if the opening bracket occurs to the left of the corresponding closing bracket respectively. If the brackets enclosed in a string are not matched, bracket pairs are not balanced. In the same way, a string having non-bracket characters such as a-z, A-Z, 0-9 and other special characters such as #, $, and @ is also considered to be unbalanced. Example "{[(])}"It is an unbalanced input string because the pair of round brackets, "()", encloses a single unbalanced closing square bracket, "]", and the pair of square brackets, "[]", encloses a single unbalanced opening round bracket, "(". A string having brackets is said to be balanced if:
Note 1: Null is considered to be balanced.Note 2: Empty string is considered to be balanced.Algorithm (Deque)
We can implement the code for balanced parentheses by using simple for loop, Deque and stack. BalancedParenthesesExample1.java Output: BalancedParenthesesExample2.java Output: BalancedParenthesesExample3.java Output: Next TopicCaesar Cipher Program in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India