Checking if parenthesis are balanced or not using Stack? - java

I have written a java code to test if an expression is balanced or not, that is, this program checks if the characters '(', '{' and '[' have a corresponding delimiter or not. However I am unable to get the required answer. There is something wrong and I am unable to figure it out and hence would need your help. Here is the code.
package z_Stack_InfixToPostfix;
import java.util.Stack;
public class Driver_InfixToPostfix {
public static void main(String[] args) {
String s="(a+b)";
System.out.println(checkBalance(s));
}
public static boolean checkBalance(String expression){
boolean isBalanced=true;
Stack<Character> myStack=new Stack<Character>();
int length=expression.length();
int i=0;
while(isBalanced && i<length){
switch(expression.charAt(i)){
case '(': case '{': case '[' :
myStack.push(expression.charAt(i));
break;
case ')': case '}': case ']':
if(myStack.isEmpty()){
isBalanced=false;
}
else{
char opendelimiter=myStack.pop();
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
}
break;
}
i++;
}
if(!myStack.isEmpty()){
isBalanced=false;
}
return isBalanced;
}
}

char opendelimiter=myStack.pop();
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
Here you should check
if(openedDeimilter == '('){
if(expression.charAt(i)!=')'){
isBalanced=false;
//break;
}
}else if(openedDeimilter == '['){
if(expression.charAt(i)!=']'){
isBalanced=false;
//break;
}
}else {
if(expression.charAt(i)!='}'){
isBalanced=false;
//break;
}
}
Also once isBalanced is set to false you can skip iterating the remaining string, if it suits you.

What about a different approach using only the length of your expression without each parentheses? This will let you not use the Stack class and should be more efficient for longer expression
public static boolean checkBalance(String expression) {
String[] parentheses = new String[]{"\\(|\\)","\\[|\\]","\\{|\\}"};
int length = expression.length();
for(int i=0; i<parentheses.length; i++) {
int newLength = expression.replaceAll(parentheses[i], "").length();
int diff = length - newLength;
if(diff % 2 != 0) {
return false;
}
}
return true;
}
The double backslash are used to escape each parentheses because they are special characters

This part is wrong:
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
You check if two chars are equal, but the correct check should match the 2 corresponding chars: [ - ], ( - ) and { - }

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char exp[1028];
char ext[1028];
int top = -1;
//-----------------------------------------------------------------------------
push(char x){
top++;
ext[top]=x;
}
//-----------------------------------------------------------------------------------------
void pop(){
top--;
}
//--------------------------------------------------------------------------------------
main()
{
int ans;
char in='{';
char it='[';
char ie='(';
char an;'}';
char at=']';
char ae=')';
printf("\nenter your expression\n");
gets(exp);
int j=strlen(exp);
int i;
for(i=0;i<=j;i++){
if(exp[i] == in || exp[i] == it || exp[i]==ie){
push(exp[i]);
}
if(exp[i] == an ||exp[i]== at || exp[i]==ae){
pop();
}
}
if(top == -1){
printf("\nexp is balanced\n");
}
else{
printf("\nexp is unbalanced");
}
}

Related

Fails for the testcase "([}}])" to validate expression(balancing parenthesis problem) which is coded in java

This code is written when I was trying to solve the problem on Leet code(the link to the problem is given below), which performs the balancing parenthesis but failing for the condition ([}}]) could anyone help me.
Thank you.
problem link---> https://leetcode.com/problems/valid-parentheses/
import java.util.*;
public class expressionValidation
{
public static void main(String[] args)
{
try (Scanner sc = new Scanner(System.in))/*trying to avoid any kind of exceptions*/
{
String str = sc.nextLine();
String exp = "";/*new string to modify the given expression*/
int l = str.length();
for(int i=0;i<l;i++)
{
if(str.charAt(i)=='{'||str.charAt(i)=='('||str.charAt(i)=='['||str.charAt(i)=='}'||str.charAt(i)==']'||str.charAt(i)==')')
{
exp+=str.substring(i,i+1);/*newly modified string afterstrong text removing everything except brackets'(' '[' '{' ' }' ']' ')'*/
}
}
stack ob = new stack();
System.out.println(ob.isValid(exp)?"Balanced":"NOT Balanced");
}
}
}
## The following is the stack class
class stack
{
boolean isValid(String exp)
{
int l =exp.length();
if(l%2!=0)
return false;
Stack<Character> st = new Stack<Character>();
for(int i=0;i<l;i++)
{
if(exp.charAt(i)=='{' ||exp.charAt(i)=='(' ||exp.charAt(i)=='[' ) {
st.push(exp.charAt(i));
}
else if(exp.charAt(i)=='}' && !(st.isEmpty()) && st.peek()=='{') {
st.pop();
}
else if(exp.charAt(i)==')' && !(st.isEmpty()) && st.peek()=='(') {
st.pop();
}
else if(exp.charAt(i)==']' && !(st.isEmpty()) && st.peek()=='[') {
st.pop();
}
String str = st.toString();
System.out.println(str);
}
return st.isEmpty();
}
}
My LeetCode submission :-
public boolean isValid(String s) {
Stack<Character> sc = new Stack<>();
for(int i =0;i<s.length();i++){
char ch = s.charAt(i);
if(ch == '(' || ch == '{' || ch == '['){
sc.push(ch);
}else if(ch == ')'){
if(!sc.isEmpty() && sc.peek() == '('){
sc.pop();
}else{
return false;
}
}else if(ch == '}'){
if(!sc.isEmpty() && sc.peek() == '{'){
sc.pop();
}else{
return false;
}
}else if(ch == ']'){
if(!sc.isEmpty() && sc.peek() == '['){
sc.pop();
}else{
return false;
}
}
}
if(sc.isEmpty()){
return true;
}else{
return false;
}
}
Try this.
boolean isValid(String s) {
int max = s.length(), index = 0;
char[] stack = new char[max];
for (int i = 0; i < max; ++i) {
char c = s.charAt(i);
switch (c) {
case '(': stack[index++] = ')'; break;
case '[': stack[index++] = ']'; break;
case '{': stack[index++] = '}'; break;
default:
if (index <= 0 || stack[--index] != c)
return false;
break;
}
}
return index == 0;
}
When you encounter } and the following condition fails
else if(exp.charAt(i)=='}' && !(st.isEmpty()) && st.peek()=='{') {
you should already produce an error, but you just silently ignore the incoming } and continue the iteration. So all unpaired closing parenthesis/brackets are just silently removed from your input. Instead of ([}}]) you analyze ([]) which is a balanced string, so you get no error.
Same is true for other closing characters as well.

Infix to Postfix Using Stacks - Java

I am trying to learn and implement some practical uses of stacks and I am doing a little program that takes in an equation and converts it to postfix notation. I am aware of how postfix notation, stacks and precedence works so the syntax approach I took seems to make sense to me however it seems to print it out in some sort of prefix notation with some duplicates at times, its really odd. Any help would be appreciated and I'll leave all of my code for you guys below, thank you.
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
infixToPostfix();
}
private static int Precedence(char character) {
System.out.print("" + character);
switch (character) {
case '+':
case '-':
return 1;
case '/':
case '*':
return 2;
case '^':
return 3;
}
return -1;
}
private static String infixToPostfix() {
Scanner scanner = new Scanner(System.in);
Stack<Character> operatorStack = new Stack<>();
System.out.println("please enter your equation");
String equation = scanner.nextLine();
StringBuilder result = new StringBuilder();
for (int i = 0; i < equation.length(); i++) {
char ch = equation.charAt(i);
if (Character.isDigit(ch)) {
result.append(ch);
} else if (ch == '(') {
operatorStack.push(ch);
} else if (operatorStack.isEmpty()
&& !Character.isDigit(ch)) {
operatorStack.push(ch);
} else {
while (!operatorStack.isEmpty()) {
if (!Character.isDigit(ch)
&& Precedence(
ch) < operatorStack
.peek()) {
result.append(operatorStack.pop());
} else if (!Character.isDigit(ch)
&& Precedence(
ch) > operatorStack
.peek()) {
operatorStack.push(ch);
} else if (ch == ')') {
result.append(operatorStack.pop());
}
}
}
}
System.out.println(result);
return result.toString();
}
}
2*(3+1) // input
++23(*1 // output
31+2* // expected output
Process finished with exit code 0

Having trouble checking to see if a string is balanced or not

package edu.bsu.cs121.mamurphy;
import java.util.Stack;
public class Checker {
char openPara = '(';
char openBracket = '[';
char openCurly = '{';
char openArrow = '<';
char closePara = ')';
char closeBracket = ']';
char closeCurly = '}';
char closeArrow = '>';
public boolean checkString(String stringToCheck) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < stringToCheck.length(); i++) {
char c = stringToCheck.charAt(i);
if (c == openPara || c == openBracket || c == openCurly || c == openArrow) {
stack.push(c);
System.out.println(stack);
;
}
if (c == closePara) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openPara) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
if (c == closeBracket) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openBracket) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
if (c == closeCurly) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openCurly) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
if (c == closeArrow) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openArrow) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
}
return false;
}
}
I am currently trying to create a program where I check to see if a string is balanced or not. A string is balanced if and only if each opening character: (, {, [, and < have a matching closing character: ), }, ], and > respectively.
What happens is when checking through the string, if an opening character is found, it is pushed into a stack, and it checks to see if there is the appropriate closing character.
If there is a closing character before the opening character, then that automatically means that the string is unbalanced. Also, the string is automatically unbalanced if after going to the next character there is something still inside of the stack.
I tried to use
else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
as a way of seeing if the stack still had anything in it, but it still isn't working for me. Any advice on what to do?
For example, if the string input were ()<>{() then the program should run through like normal until it gets to the single { and then the code should realize that the string is unbalanced and output Unbalanced.
For whatever reason, my code does not do this.
The following logic is flawed (emphasis mine):
For example, if the string input were ()<>{() then the program should run through like normal until it gets to the single { and then the code should realize that the string is unbalanced and output Unbalanced.
In fact, the code can't conclude that the string is unbalanced until it has scanned the entire string and established that the { has no matching }. For all it knows, the full input could be ()<>{()} and be balanced.
To achieve this, you need to add a check that ensures that the stack is empty after the entire string has been processes. In your example, it would still contain the {, indicating that the input is not balanced.
I took a shot at answering this. My solutions returns true if the string is balanced and enforces opening/closing order (ie ({)} returns false). I started with your code and tried to slim it down.
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class mamurphy {
private static final char openPara = '(';
private static final char openBracket = '[';
private static final char openCurly = '{';
private static final char openArrow = '<';
private static final char closePara = ')';
private static final char closeBracket = ']';
private static final char closeCurly = '}';
private static final char closeArrow = '>';
public static void main(String... args) {
System.out.println(checkString("{}[]()90<>"));//true
System.out.println(checkString("(((((())))"));//false
System.out.println(checkString("((())))"));//false
System.out.println(checkString(">"));//false
System.out.println(checkString("["));//false
System.out.println(checkString("{[(<>)]}"));//true
System.out.println(checkString("{[(<>)}]"));//false
System.out.println(checkString("( a(b) (c) (d(e(f)g)h) I (j<k>l)m)"));//true
}
public static boolean checkString(String stringToCheck) {
final Map<Character, Character> closeToOpenMap = new HashMap<>();
closeToOpenMap.put(closePara, openPara);
closeToOpenMap.put(closeBracket, openBracket);
closeToOpenMap.put(closeCurly, openCurly);
closeToOpenMap.put(closeArrow, openArrow);
Stack<Character> stack = new Stack<>();
final char[] stringAsChars = stringToCheck.toCharArray();
for (int i = 0; i < stringAsChars.length; i++) {
final char current = stringAsChars[i];
if (closeToOpenMap.values().contains(current)) {
stack.push(current); //found an opening char, push it!
} else if (closeToOpenMap.containsKey(current)) {
if (stack.isEmpty() || closeToOpenMap.get(current) != stack.pop()) {
return false;//found closing char without correct opening char on top of stack
}
}
}
if (!stack.isEmpty()) {
return false;//still have opening chars after consuming whole string
}
return true;
}
}
Here's an alternate approach:
private static final char[] openParens = "[({<".toCharArray();
private static final char[] closeParens = "])}>".toCharArray();
public static boolean isBalanced(String expression){
Deque<Character> stack = new ArrayDeque<>();
for (char c : expression.toCharArray()){
for (int i = 0; i < openParens.length; i++){
if (openParens[i] == c){
// This is an open - put it in the stack
stack.push(c);
break;
}
if (closeParens[i] == c){
// This is a close - check the open is at the top of the stack
if (stack.poll() != openParens[i]){
return false;
}
break;
}
}
}
return stack.isEmpty();
}
It simplifies the logic to have two corresponding arrays of open and close symbols. You could also do this with even and odd positions in one array - ie. "{}<>", for example:
private static final char[] symbols = "[](){}<>".toCharArray();
public static boolean isBalanced(String expression){
Deque<Character> stack = new ArrayDeque<>();
for (char c : expression.toCharArray()){
for (int i = 0; i < symbols.length; i += 2){
if (symbols[i] == c){
// This is an open - put it in the stack
stack.push(c);
break;
}
if (symbols[i + 1] == c){
// This is a close - check the open is at the top of the stack
if (stack.poll() != symbols[i]){
return false;
}
break;
}
}
}
return stack.isEmpty();
}
Note that poll returns null if the stack is empty, so will correctly fail the equality comparison if we run out of stack.
For example, if the string input were ()<>{() then the program should run through like normal until it gets to the single { and then the code should realize that the string is unbalanced and output Unbalanced.
It is not clear by your example whether the boundaries can be nested like ([{}]). If they can, that logic will not work, as the whole string has to be consumed to be sure any missing closing-chars aren't at the end, and so, the string cannot be reliably deemed unbalanced at the point you indicate.
Here is my take on your problem:
BalanceChecker class:
package so_q33378870;
import java.util.Stack;
public class BalanceChecker {
private final char[] opChars = "([{<".toCharArray();
private final char[] edChars = ")]}>".toCharArray();
//<editor-fold defaultstate="collapsed" desc="support functions">
public boolean isOPChar(char c) {
for (char checkChar : opChars) {
if (c == checkChar) {
return true;
}
}
return false;
}
public boolean isEDChar(char c) {
for (char checkChar : edChars) {
if (c == checkChar) {
return true;
}
}
return false;
}
//NOTE: Unused.
// public boolean isBoundaryChar(char c) {
// boolean result;
// if (result = isOPChar(c) == false) {
// return isEDChar(c);
// } else {
// return result;
// }
// }
public char getOpCharFor(char c) {
for (int i = 0; i < edChars.length; i++) {
if (c == edChars[i]) {
return opChars[i];
}
}
throw new IllegalArgumentException("The character (" + c + ") received is not recognized as a closing boundary character.");
}
//</editor-fold>
public boolean isBalanced(char[] charsToCheck) {
Stack<Character> checkStack = new Stack<>();
for (int i = 0; i < charsToCheck.length; i++) {
if (isOPChar(charsToCheck[i])) {
//beginning char found. Add to top of stack.
checkStack.push(charsToCheck[i]);
} else if (isEDChar(charsToCheck[i])) {
if (checkStack.isEmpty()) {
//ending char found without beginning chars on the stack. UNBALANCED.
return false;
} else if (getOpCharFor(charsToCheck[i]) == checkStack.peek()) {
//ending char found matches last beginning char on the stack. Pop and continue.
checkStack.pop();
} else {
//ending char found, but doesn't match last beginning char on the stack. UNBALANCED.
return false;
}
}
}
//the string is balanced if and only if the stack is empty at the end.
return checkStack.empty();
}
public boolean isBalanced(String stringToCheck) {
return isBalanced(stringToCheck.toCharArray());
}
}
Main class (used for testing):
package so_q33378870;
public class main {
private static final String[] tests = {
//Single - Balanced.
"()",
//Single - Unbalanced by missing end.
"(_",
//Multiple - Balanced.
"()[]{}<>",
//Multiple - Unbalanced by missing beginning.
"()[]_}<>",
//Nested - Balanced.
"([{<>}])",
//Nested - Unbalanced by missing end.
"([{<>}_)",
//Endurance test - Balanced.
"the_beginning (abcd) divider (a[bc]d) divider (a[b{c}d]e) divider (a[b{c<d>e}f]g) the_end"
};
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
BalanceChecker checker = new BalanceChecker();
for (String s : tests) {
System.out.println("\"" + s + "\" is " + ((checker.isBalanced(s)) ? "BALANCED!" : "UNBALANCED!"));
}
}
}

What are the cases to be considered while parsing a mathematical expression(brackets)? [duplicate]

For example if the parenthesis/brackets is matching in the following:
({})
(()){}()
()
and so on but if the parenthesis/brackets is not matching it should return false, eg:
{}
({}(
){})
(()
and so on. Can you please check this code?
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '{')
return false;
if(c == '(')
stack.push(c);
if(c == '{') {
stack.push(c);
if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
}
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
}
return stack.empty();
}
public static void main(String[] args) {
String str = "({})";
System.out.println(Weekly12.parenthesisOtherMatching(str));
}
Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.
This code, modified slightly from yours, seems to work properly:
public static boolean isParenthesisMatch(String str) {
if (str.charAt(0) == '{')
return false;
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '(')
stack.push(c);
else if(c == '{')
stack.push(c);
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
else if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
else
return false;
}
return stack.empty();
}
This code is easier to understand:
public static boolean CheckParentesis(String str)
{
if (str.isEmpty())
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
The algorithm:
scan the string,pushing to a stack for every '(' found in the string
if char ')' scanned, pop one '(' from the stack
Now, parentheses are balanced for two conditions:
'(' can be popped from the stack for every ')' found in the string, and
stack is empty at the end (when the entire string is processed)
Actually, there is no need to check any cases "manually". You can just run the following algorithm:
Iterate over the given sequence. Start with an empty stack.
If the current char is an opening bracket, just push it to the stack.
If it's a closing bracket, check that the stack is not empty and the top element of the step is an appropriate opening bracket(that it is, matches this one). If it is not, report an error. Otherwise, pop the top element from the stack.
In the end, the sequence is correct iff the stack is empty.
Why is it correct? Here is a sketch of a proof: if this algorithm reported that the sequence is corrected, it had found a matching pair of all brackets. Thus, the sequence is indeed correct by definition. If it has reported an error:
If the stack was not empty in the end, the balance of opening and closing brackets is not zero. Thus, it is not a correct sequence.
If the stack was empty when we had to pop an element, the balance is off again.
If there was a wrong element on top of the stack, a pair of "wrong" brackets should match each other. It means that the sequence is not correct.
I have shown that:
If the algorithm has reported that the sequence is correct, it is correct.
If the algorithm has reported that the sequence is not correct, it is incorrect(note that I do not use the fact that there are no other cases except those that are mentioned in your question).
This two points imply that this algorithm works for all possible inputs.
public static boolean isBalanced(String s) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put('(', ')');
openClosePair.put('{', '}');
openClosePair.put('[', ']');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (openClosePair.containsKey(s.charAt(i))) {
stack.push(s.charAt(i));
} else if ( openClosePair.containsValue(s.charAt(i))) {
if (stack.isEmpty())
return false;
if (openClosePair.get(stack.pop()) != s.charAt(i))
return false;
}
// ignore all other characters
}
return stack.isEmpty();
}
Ganesan's answer above is not correct and StackOverflow is not letting me comment or Edit his post. So below is the correct answer. Ganesan has an incorrect facing "[" and is missing the stack isEmpty() check.
The below code will return true if the braces are properly matching.
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.isEmpty() || stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
You're doing some extra checks that aren't needed. Doesn't make any diff to functionality, but a cleaner way to write your code would be:
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (c == '(' || c == '{')
stack.push(c);
else if (stack.empty())
return false;
else if (c == ')') {
if (stack.pop() != '(')
return false;
} else if (c == '}') {
if (stack.pop() != '{')
return false;
}
}
return stack.empty();
}
There is no reason to peek at a paranthesis before removing it from the stack. I'd also consider wrapping instruction blocks in parantheses to improve readability.
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(map.containsKey(c)){
stack.push(c);
} else if(!stack.empty() && map.get(stack.peek())==c){
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
Algorithm is:
1)Create a stack
2)while(end of input is not reached)
i)if the character read is not a sysmbol to be balanced ,ignore it.
ii)if the character is {,[,( then push it to stack
iii)If it is a },),] then if
a)the stack is empty report an error(catch it) i.e not balanced
b)else pop the stack
iv)if element popped is not corresponding to opening sysmbol,then report error.
3) In the end,if stack is not empty report error else expression is balanced.
In Java code:
public class StackDemo {
public static void main(String[] args) throws Exception {
System.out.println("--Bracket checker--");
CharStackArray stack = new CharStackArray(10);
stack.balanceSymbol("[a+b{c+(e-f[p-q])}]") ;
stack.display();
}
}
class CharStackArray {
private char[] array;
private int top;
private int capacity;
public CharStackArray(int cap) {
capacity = cap;
array = new char[capacity];
top = -1;
}
public void push(char data) {
array[++top] = data;
}
public char pop() {
return array[top--];
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + "->");
}
}
public char peek() throws Exception {
return array[top];
}
/*Call this method by passing a string expression*/
public void balanceSymbol(String str) {
try {
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '[' || arr[i] == '{' || arr[i] == '(')
push(arr[i]);
else if (arr[i] == '}' && peek() == '{')
pop();
else if (arr[i] == ']' && peek() == '[')
pop();
else if (arr[i] == ')' && peek() == '(')
pop();
}
if (isEmpty()) {
System.out.println("String is balanced");
} else {
System.out.println("String is not balanced");
}
} catch (Exception e) {
System.out.println("String not balanced");
}
}
public boolean isEmpty() {
return (top == -1);
}
}
Output:
--Bracket checker--
String is balanced
Optimized implementation using Stacks and Switch statement:
public class JavaStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Character> s = new Stack<Character>();
while (sc.hasNext()) {
String input = sc.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '(':
s.push(c); break;
case '[':
s.push(c); break;
case '{':
s.push(c); break;
case ')':
if (!s.isEmpty() && s.peek().equals('(')) {
s.pop();
} else {
s.push(c);
} break;
case ']':
if (!s.isEmpty() && s.peek().equals('[')) {
s.pop();
} else {
s.push(c);
} break;
case '}':
if (!s.isEmpty() && s.peek().equals('{')) {
s.pop();
} else {
s.push(c);
} break;
default:
s.push('x'); break;
}
}
if (s.empty()) {
System.out.println("true");
} else {
System.out.println("false");
s.clear();
}
}
} }
Cheers !
import java.util.*;
class StackDemo {
public static void main(String[] argh) {
boolean flag = true;
String str = "(()){}()";
int l = str.length();
flag = true;
Stack<String> st = new Stack<String>();
for (int i = 0; i < l; i++) {
String test = str.substring(i, i + 1);
if (test.equals("(")) {
st.push(test);
} else if (test.equals("{")) {
st.push(test);
} else if (test.equals("[")) {
st.push(test);
} else if (test.equals(")")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("(")) {
st.pop();
} else {
flag = false;
break;
}
} else if (test.equals("}")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("{")) {
st.pop();
} else {
flag = false;
break;
}
} else if (test.equals("]")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("[")) {
st.pop();
} else {
flag = false;
break;
}
}
}
if (flag && st.empty())
System.out.println("true");
else
System.out.println("false");
}
}
I have seen answers here and almost all did well. However, I have written my own version that utilizes a Dictionary for managing the bracket pairs and a stack to monitor the order of detected braces. I have also written a blog post for this.
Here is my class
public class FormulaValidator
{
// Question: Check if a string is balanced. Every opening bracket is matched by a closing bracket in a correct position.
// { [ ( } ] )
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{ ( [ ) ] }" is _not_ balanced
// Input: string, containing the bracket symbols only
// Output: true or false
public bool IsBalanced(string input)
{
var brackets = BuildBracketMap();
var openingBraces = new Stack<char>();
var inputCharacters = input.ToCharArray();
foreach (char character in inputCharacters)
{
if (brackets.ContainsKey(character))
{
openingBraces.Push(character);
}
if (brackets.ContainsValue(character))
{
var closingBracket = character;
var openingBracket = brackets.FirstOrDefault(x => x.Value == closingBracket).Key;
if (openingBraces.Peek() == openingBracket)
openingBraces.Pop();
else
return false;
}
}
return openingBraces.Count == 0;
}
private Dictionary<char, char> BuildBracketMap()
{
return new Dictionary<char, char>()
{
{'[', ']'},
{'(', ')'},
{'{', '}'}
};
}
}
Algorithm to use for checking well balanced parenthesis -
Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
Declare a set openingParenSet and initialize it with the values of matchingParenMap.
Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
Now traverse the string expression input.
If the current character is an opening bracket ( '{', '(', '[' ) then push it to the
parenStack.
If the current character is a closing bracket ( '}', ')', ']' ) then pop from
parenStack and if the popped character is equal to the matching starting bracket in
matchingParenMap then continue looping else return false.
After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.
I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
Problem Statement:
Check for balanced parentheses in an expression Or Match for Open Closing Brackets
If you appeared for coding interview round then you might have encountered this problem before. This is a pretty common question and can be solved by using Stack Data Structure
Solution in C#
public void OpenClosingBracketsMatch()
{
string pattern = "{[(((((}}])";
Dictionary<char, char> matchLookup = new Dictionary<char, char>();
matchLookup['{'] = '}';
matchLookup['('] = ')';
matchLookup['['] = ']';
Stack<char> stck = new Stack<char>();
for (int i = 0; i < pattern.Length; i++)
{
char currentChar = pattern[i];
if (matchLookup.ContainsKey(currentChar))
stck.Push(currentChar);
else if (currentChar == '}' || currentChar == ')' || currentChar == ']')
{
char topCharFromStack = stck.Peek();
if (matchLookup[topCharFromStack] != currentChar)
{
Console.WriteLine("NOT Matched");
return;
}
}
}
Console.WriteLine("Matched");
}
For more information, you may also refer to this link: https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
here is my solution using c++
if brackets are matched then returns true if not then gives false
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
int matchbracket(string expr){
stack<char> st;
int i;
char x;
for(i=0;i<expr.length();i++){
if(expr[i]=='('||expr[i]=='{'||expr[i]=='[')
st.push(expr[i]);
if(st.empty())
return -1;
switch(expr[i]){
case ')' :
x=expr[i];
st.pop();
if(x=='}'||x==']')
return 0;
break;
case '}' :
x=expr[i];
st.pop();
if(x==')'||x==']')
return 0;
break;
case ']' :
x=expr[i];
st.pop();
if(x==')'||x=='}')
return 1;
break;
}
}
return(st.empty());
}
int main()
{
string expr;
cin>>expr;
if(matchbracket(expr)==1)
cout<<"\nTRUE\n";
else
cout<<"\nFALSE\n";
}
This is my implementation for this problem:
public class BalancedBrackets {
static final Set<Character> startBrackets = Set.of('(', '[', '{');
static final Map<Character, Character> bracketsMap = Map.of('(', ')', '[', ']', '{', '}');
public static void main(String[] args) {
// Here you can add test cases
Arrays.asList(
"(())",
"([])",
"()()(())({})"
).forEach(expTest -> System.out.printf("%s is %s balanced%n", expTest, isBalancedBrackets(expTest) ? "" : "not"));
}
public static boolean isBalancedBrackets(String exp) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < exp.length(); i++) {
Character chr = exp.charAt(i);
if (bracketsMap.containsKey(chr)) {
stack.push(chr);
continue;
}
if (stack.isEmpty()) {
return false;
}
Character check = stack.pop();
if (bracketsMap.get(check) != chr) {
return false;
}
}
return (stack.isEmpty());
}
}
https://github.com/CMohamed/ProblemSolving/blob/main/other/balanced-brackets/BalancedBrackets.java
//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))->
//Split string to substring {[()]}, next [], next [], next{}
public class testbrackets {
static String stringfirst;
static String stringsecond;
static int open = 0;
public static void main(String[] args) {
splitstring("(()){}()");
}
static void splitstring(String str){
int len = str.length();
for(int i=0;i<=len-1;i++){
stringfirst="";
stringsecond="";
System.out.println("loop starttttttt");
char a = str.charAt(i);
if(a=='{'||a=='['||a=='(')
{
open = open+1;
continue;
}
if(a=='}'||a==']'||a==')'){
if(open==0){
System.out.println(open+"started with closing brace");
return;
}
String stringfirst=str.substring(i-open, i);
System.out.println("stringfirst"+stringfirst);
String stringsecond=str.substring(i, i+open);
System.out.println("stringsecond"+stringsecond);
replace(stringfirst, stringsecond);
}
i=(i+open)-1;
open=0;
System.out.println(i);
}
}
static void replace(String stringfirst, String stringsecond){
stringfirst = stringfirst.replace('{', '}');
stringfirst = stringfirst.replace('(', ')');
stringfirst = stringfirst.replace('[', ']');
StringBuilder stringfirst1 = new StringBuilder(stringfirst);
stringfirst = stringfirst1.reverse().toString();
System.out.println("stringfirst"+stringfirst);
System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
System.out.println("pass");
}
else{
System.out.println("fail");
System.exit(0);
}
}
}
import java.util.Stack;
class Demo
{
char c;
public boolean checkParan(String word)
{
Stack<Character> sta = new Stack<Character>();
for(int i=0;i<word.length();i++)
{
c=word.charAt(i);
if(c=='(')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c=='{')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c==')')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='(')
{
sta.pop();
System.out.println(" ) is poped from the Stack");
}
else if(sta.peek()=='(' && sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
}
else if(c=='}')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='{')
{
sta.pop();
System.out.println(" } is poped from the Stack");
}
}
else if(c=='(')
{
if(sta.empty())
{
System.out.println("Stack is empty only ( parenthesis in Stack ");
}
}
}
// System.out.print("The top element is : "+sta.peek());
return sta.empty();
}
}
public class ParaenthesisChehck {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Demo d1= new Demo();
// d1.checkParan(" ");
// d1.checkParan("{}");
//d1.checkParan("()");
//d1.checkParan("{()}");
// d1.checkParan("{123}");
d1.checkParan("{{{}}");
}
}
import java.util.*;
public class Parenthesis
{
public static void main(String...okok)
{
Scanner sc= new Scanner(System.in);
String str=sc.next();
System.out.println(isValid(str));
}
public static int isValid(String a) {
if(a.length()%2!=0)
{
return 0;
}
else if(a.length()==0)
{
return 1;
}
else
{
char c[]=a.toCharArray();
Stack<Character> stk = new Stack<Character>();
for(int i=0;i<c.length;i++)
{
if(c[i]=='(' || c[i]=='[' || c[i]=='{')
{
stk.push(c[i]);
}
else
{
if(stk.isEmpty())
{
return 0;
//break;
}
else
{
char cc=c[i];
if(cc==')' && stk.peek()=='(' )
{
stk.pop();
}
else if(cc==']' && stk.peek()=='[' )
{
stk.pop();
}
else if(cc=='}' && stk.peek()=='{' )
{
stk.pop();
}
}
}
}
if(stk.isEmpty())
{
return 1;
}else
{
return 0;
}
}
}
}
I tried this using javascript below is the result.
function bracesChecker(str) {
if(!str) {
return true;
}
var openingBraces = ['{', '[', '('];
var closingBraces = ['}', ']', ')'];
var stack = [];
var openIndex;
var closeIndex;
//check for opening Braces in the val
for (var i = 0, len = str.length; i < len; i++) {
openIndex = openingBraces.indexOf(str[i]);
closeIndex = closingBraces.indexOf(str[i]);
if(openIndex !== -1) {
stack.push(str[i]);
}
if(closeIndex !== -1) {
if(openingBraces[closeIndex] === stack[stack.length-1]) {
stack.pop();
} else {
return false;
}
}
}
if(stack.length === 0) {
return true;
} else {
return false;
}
}
var testStrings = [
'',
'test',
'{{[][]()()}()}[]()',
'{test{[test]}}',
'{test{[test]}',
'{test{(yo)[test]}}',
'test{[test]}}',
'te()s[]t{[test]}',
'te()s[]t{[test'
];
testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));
import java.util.*;
public class MatchBrackets {
public static void main(String[] argh) {
String input = "[]{[]()}";
System.out.println (input);
char [] openChars = {'[','{','('};
char [] closeChars = {']','}',')'};
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
String x = "" +input.charAt(i);
if (String.valueOf(openChars).indexOf(x) != -1)
{
stack.push(input.charAt(i));
}
else
{
Character lastOpener = stack.peek();
int idx1 = String.valueOf(openChars).indexOf(lastOpener.toString());
int idx2 = String.valueOf(closeChars).indexOf(x);
if (idx1 != idx2)
{
System.out.println("false");
return;
}
else
{
stack.pop();
}
}
}
if (stack.size() == 0)
System.out.println("true");
else
System.out.println("false");
}
}
If you want to have a look at my code. Just for reference
public class Default {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfString = Integer.parseInt(br.readLine());
String s;
String stringBalanced = "YES";
Stack<Character> exprStack = new Stack<Character>();
while ((s = br.readLine()) != null) {
stringBalanced = "YES";
int length = s.length() - 1;
for (int i = 0; i <= length; i++) {
char tmp = s.charAt(i);
if(tmp=='[' || tmp=='{' || tmp=='('){
exprStack.push(tmp);
}else if(tmp==']' || tmp=='}' || tmp==')'){
if(!exprStack.isEmpty()){
char peekElement = exprStack.peek();
exprStack.pop();
if(tmp==']' && peekElement!='['){
stringBalanced="NO";
}else if(tmp=='}' && peekElement!='{'){
stringBalanced="NO";
}else if(tmp==')' && peekElement!='('){
stringBalanced="NO";
}
}else{
stringBalanced="NO";
break;
}
}
}
if(!exprStack.isEmpty()){
stringBalanced = "NO";
}
exprStack.clear();
System.out.println(stringBalanced);
}
}
}
public static bool IsBalanced(string input)
{
Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
{ '<', '>' }
};
Stack<char> brackets = new Stack<char>();
try
{
// Iterate through each character in the input string
foreach (char c in input)
{
// check if the character is one of the 'opening' brackets
if (bracketPairs.Keys.Contains(c))
{
// if yes, push to stack
brackets.Push(c);
}
else
// check if the character is one of the 'closing' brackets
if (bracketPairs.Values.Contains(c))
{
// check if the closing bracket matches the 'latest' 'opening' bracket
if (c == bracketPairs[brackets.First()])
{
brackets.Pop();
}
else
// if not, its an unbalanced string
return false;
}
else
// continue looking
continue;
}
}
catch
{
// an exception will be caught in case a closing bracket is found,
// before any opening bracket.
// that implies, the string is not balanced. Return false
return false;
}
// Ensure all brackets are closed
return brackets.Count() == 0 ? true : false;
}
public String checkString(String value) {
Stack<Character> stack = new Stack<>();
char topStackChar = 0;
for (int i = 0; i < value.length(); i++) {
if (!stack.isEmpty()) {
topStackChar = stack.peek();
}
stack.push(value.charAt(i));
if (!stack.isEmpty() && stack.size() > 1) {
if ((topStackChar == '[' && stack.peek() == ']') ||
(topStackChar == '{' && stack.peek() == '}') ||
(topStackChar == '(' && stack.peek() == ')')) {
stack.pop();
stack.pop();
}
}
}
return stack.isEmpty() ? "YES" : "NO";
}
Here's a solution in Python.
#!/usr/bin/env python
def brackets_match(brackets):
stack = []
for char in brackets:
if char == "{" or char == "(" or char == "[":
stack.append(char)
if char == "}":
if stack[-1] == "{":
stack.pop()
else:
return False
elif char == "]":
if stack[-1] == "[":
stack.pop()
else:
return False
elif char == ")":
if stack[-1] == "(":
stack.pop()
else:
return False
if len(stack) == 0:
return True
else:
return False
if __name__ == "__main__":
print(brackets_match("This is testing {([])} if brackets have match."))
Was asked to implement this algorithm at live coding interview, here's my refactored solution in C#:
Git Tests
package com.balance.braces;
import java.util.Arrays;
import java.util.Stack;
public class BalanceBraces {
public static void main(String[] args) {
String[] values = { "()]", "[()]" };
String[] rsult = match(values);
Arrays.stream(rsult).forEach(str -> System.out.println(str));
}
static String[] match(String[] values) {
String[] returnString = new String[values.length];
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value.length() % 2 != 0) {
returnString[i] = "NO";
continue;
} else {
Stack<Character> buffer = new Stack<Character>();
for (char ch : value.toCharArray()) {
if (buffer.isEmpty()) {
buffer.add(ch);
} else {
if (isMatchedBrace(buffer.peek(), ch)) {
buffer.pop();
} else {
buffer.push(ch);
}
}
if (buffer.isEmpty()) {
returnString[i] = "YES";
} else {
returnString[i] = "FALSE";
}
}
}
}
return returnString;
}
static boolean isMatchedBrace(char start, char endmatch) {
if (start == '{')
return endmatch == '}';
if (start == '(')
return endmatch == ')';
if (start == '[')
return endmatch == ']';
return false;
}
}
in java you don't want to compare the string or char by == signs. you would use equals method. equalsIgnoreCase or something of the like. if you use == it must point to the same memory location. In the method below I attempted to use ints to get around this. using ints here from the string index since every opening brace has a closing brace. I wanted to use location match instead of a comparison match. But i think with this you have to be intentional in where you place the characters of the string. Lets also consider that Yes = true and No = false for simplicity. This answer assumes that you passed an array of strings to inspect and required an array of if yes (they matched) or No (they didn't)
import java.util.Stack;
public static void main(String[] args) {
//String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","{}","}]{}","{[)]()}"};
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{([)]}" is _not_ balanced
String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","()[]{}","}]{}","{[)]()}","{[)]()}","{([)]}"};
String[] answers = new String[arrayOfBraces.length];
String openers = "([{";
String closers = ")]}";
String stringToInspect = "";
Stack<String> stack = new Stack<String>();
for (int i = 0; i < arrayOfBraces.length; i++) {
stringToInspect = arrayOfBraces[i];
for (int j = 0; j < stringToInspect.length(); j++) {
if(stack.isEmpty()){
if (openers.indexOf(stringToInspect.charAt(j))>=0) {
stack.push(""+stringToInspect.charAt(j));
}
else{
answers[i]= "NO";
j=stringToInspect.length();
}
}
else if(openers.indexOf(stringToInspect.charAt(j))>=0){
stack.push(""+stringToInspect.charAt(j));
}
else{
String comparator = stack.pop();
int compLoc = openers.indexOf(comparator);
int thisLoc = closers.indexOf(stringToInspect.charAt(j));
if (compLoc != thisLoc) {
answers[i]= "NO";
j=stringToInspect.length();
}
else{
if(stack.empty() && (j== stringToInspect.length()-1)){
answers[i]= "YES";
}
}
}
}
}
System.out.println(answers.length);
for (int j = 0; j < answers.length; j++) {
System.out.println(answers[j]);
}
}
Check balanced parenthesis or brackets with stack--
var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
var stk = [];
function bracket_balance(){
for(var i=0;i<excp.length;i++){
if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
stk.push(excp[i]);
}else if(excp[i]== ']' && stk.pop() != '['){
return false;
}else if(excp[i]== '}' && stk.pop() != '{'){
return false;
}else if(excp[i]== ')' && stk.pop() != '('){
return false;
}
}
return true;
}
console.log(bracket_balance());
//Parenthesis are balance then return true else false

Parenthesis/Brackets Matching using Stack algorithm

For example if the parenthesis/brackets is matching in the following:
({})
(()){}()
()
and so on but if the parenthesis/brackets is not matching it should return false, eg:
{}
({}(
){})
(()
and so on. Can you please check this code?
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '{')
return false;
if(c == '(')
stack.push(c);
if(c == '{') {
stack.push(c);
if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
}
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
}
return stack.empty();
}
public static void main(String[] args) {
String str = "({})";
System.out.println(Weekly12.parenthesisOtherMatching(str));
}
Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.
This code, modified slightly from yours, seems to work properly:
public static boolean isParenthesisMatch(String str) {
if (str.charAt(0) == '{')
return false;
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '(')
stack.push(c);
else if(c == '{')
stack.push(c);
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
else if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
else
return false;
}
return stack.empty();
}
This code is easier to understand:
public static boolean CheckParentesis(String str)
{
if (str.isEmpty())
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
The algorithm:
scan the string,pushing to a stack for every '(' found in the string
if char ')' scanned, pop one '(' from the stack
Now, parentheses are balanced for two conditions:
'(' can be popped from the stack for every ')' found in the string, and
stack is empty at the end (when the entire string is processed)
Actually, there is no need to check any cases "manually". You can just run the following algorithm:
Iterate over the given sequence. Start with an empty stack.
If the current char is an opening bracket, just push it to the stack.
If it's a closing bracket, check that the stack is not empty and the top element of the step is an appropriate opening bracket(that it is, matches this one). If it is not, report an error. Otherwise, pop the top element from the stack.
In the end, the sequence is correct iff the stack is empty.
Why is it correct? Here is a sketch of a proof: if this algorithm reported that the sequence is corrected, it had found a matching pair of all brackets. Thus, the sequence is indeed correct by definition. If it has reported an error:
If the stack was not empty in the end, the balance of opening and closing brackets is not zero. Thus, it is not a correct sequence.
If the stack was empty when we had to pop an element, the balance is off again.
If there was a wrong element on top of the stack, a pair of "wrong" brackets should match each other. It means that the sequence is not correct.
I have shown that:
If the algorithm has reported that the sequence is correct, it is correct.
If the algorithm has reported that the sequence is not correct, it is incorrect(note that I do not use the fact that there are no other cases except those that are mentioned in your question).
This two points imply that this algorithm works for all possible inputs.
public static boolean isBalanced(String s) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put('(', ')');
openClosePair.put('{', '}');
openClosePair.put('[', ']');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (openClosePair.containsKey(s.charAt(i))) {
stack.push(s.charAt(i));
} else if ( openClosePair.containsValue(s.charAt(i))) {
if (stack.isEmpty())
return false;
if (openClosePair.get(stack.pop()) != s.charAt(i))
return false;
}
// ignore all other characters
}
return stack.isEmpty();
}
Ganesan's answer above is not correct and StackOverflow is not letting me comment or Edit his post. So below is the correct answer. Ganesan has an incorrect facing "[" and is missing the stack isEmpty() check.
The below code will return true if the braces are properly matching.
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.isEmpty() || stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
You're doing some extra checks that aren't needed. Doesn't make any diff to functionality, but a cleaner way to write your code would be:
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (c == '(' || c == '{')
stack.push(c);
else if (stack.empty())
return false;
else if (c == ')') {
if (stack.pop() != '(')
return false;
} else if (c == '}') {
if (stack.pop() != '{')
return false;
}
}
return stack.empty();
}
There is no reason to peek at a paranthesis before removing it from the stack. I'd also consider wrapping instruction blocks in parantheses to improve readability.
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(map.containsKey(c)){
stack.push(c);
} else if(!stack.empty() && map.get(stack.peek())==c){
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
Algorithm is:
1)Create a stack
2)while(end of input is not reached)
i)if the character read is not a sysmbol to be balanced ,ignore it.
ii)if the character is {,[,( then push it to stack
iii)If it is a },),] then if
a)the stack is empty report an error(catch it) i.e not balanced
b)else pop the stack
iv)if element popped is not corresponding to opening sysmbol,then report error.
3) In the end,if stack is not empty report error else expression is balanced.
In Java code:
public class StackDemo {
public static void main(String[] args) throws Exception {
System.out.println("--Bracket checker--");
CharStackArray stack = new CharStackArray(10);
stack.balanceSymbol("[a+b{c+(e-f[p-q])}]") ;
stack.display();
}
}
class CharStackArray {
private char[] array;
private int top;
private int capacity;
public CharStackArray(int cap) {
capacity = cap;
array = new char[capacity];
top = -1;
}
public void push(char data) {
array[++top] = data;
}
public char pop() {
return array[top--];
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + "->");
}
}
public char peek() throws Exception {
return array[top];
}
/*Call this method by passing a string expression*/
public void balanceSymbol(String str) {
try {
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '[' || arr[i] == '{' || arr[i] == '(')
push(arr[i]);
else if (arr[i] == '}' && peek() == '{')
pop();
else if (arr[i] == ']' && peek() == '[')
pop();
else if (arr[i] == ')' && peek() == '(')
pop();
}
if (isEmpty()) {
System.out.println("String is balanced");
} else {
System.out.println("String is not balanced");
}
} catch (Exception e) {
System.out.println("String not balanced");
}
}
public boolean isEmpty() {
return (top == -1);
}
}
Output:
--Bracket checker--
String is balanced
Optimized implementation using Stacks and Switch statement:
public class JavaStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Character> s = new Stack<Character>();
while (sc.hasNext()) {
String input = sc.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '(':
s.push(c); break;
case '[':
s.push(c); break;
case '{':
s.push(c); break;
case ')':
if (!s.isEmpty() && s.peek().equals('(')) {
s.pop();
} else {
s.push(c);
} break;
case ']':
if (!s.isEmpty() && s.peek().equals('[')) {
s.pop();
} else {
s.push(c);
} break;
case '}':
if (!s.isEmpty() && s.peek().equals('{')) {
s.pop();
} else {
s.push(c);
} break;
default:
s.push('x'); break;
}
}
if (s.empty()) {
System.out.println("true");
} else {
System.out.println("false");
s.clear();
}
}
} }
Cheers !
import java.util.*;
class StackDemo {
public static void main(String[] argh) {
boolean flag = true;
String str = "(()){}()";
int l = str.length();
flag = true;
Stack<String> st = new Stack<String>();
for (int i = 0; i < l; i++) {
String test = str.substring(i, i + 1);
if (test.equals("(")) {
st.push(test);
} else if (test.equals("{")) {
st.push(test);
} else if (test.equals("[")) {
st.push(test);
} else if (test.equals(")")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("(")) {
st.pop();
} else {
flag = false;
break;
}
} else if (test.equals("}")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("{")) {
st.pop();
} else {
flag = false;
break;
}
} else if (test.equals("]")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("[")) {
st.pop();
} else {
flag = false;
break;
}
}
}
if (flag && st.empty())
System.out.println("true");
else
System.out.println("false");
}
}
I have seen answers here and almost all did well. However, I have written my own version that utilizes a Dictionary for managing the bracket pairs and a stack to monitor the order of detected braces. I have also written a blog post for this.
Here is my class
public class FormulaValidator
{
// Question: Check if a string is balanced. Every opening bracket is matched by a closing bracket in a correct position.
// { [ ( } ] )
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{ ( [ ) ] }" is _not_ balanced
// Input: string, containing the bracket symbols only
// Output: true or false
public bool IsBalanced(string input)
{
var brackets = BuildBracketMap();
var openingBraces = new Stack<char>();
var inputCharacters = input.ToCharArray();
foreach (char character in inputCharacters)
{
if (brackets.ContainsKey(character))
{
openingBraces.Push(character);
}
if (brackets.ContainsValue(character))
{
var closingBracket = character;
var openingBracket = brackets.FirstOrDefault(x => x.Value == closingBracket).Key;
if (openingBraces.Peek() == openingBracket)
openingBraces.Pop();
else
return false;
}
}
return openingBraces.Count == 0;
}
private Dictionary<char, char> BuildBracketMap()
{
return new Dictionary<char, char>()
{
{'[', ']'},
{'(', ')'},
{'{', '}'}
};
}
}
Algorithm to use for checking well balanced parenthesis -
Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
Declare a set openingParenSet and initialize it with the values of matchingParenMap.
Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
Now traverse the string expression input.
If the current character is an opening bracket ( '{', '(', '[' ) then push it to the
parenStack.
If the current character is a closing bracket ( '}', ')', ']' ) then pop from
parenStack and if the popped character is equal to the matching starting bracket in
matchingParenMap then continue looping else return false.
After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.
I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
Problem Statement:
Check for balanced parentheses in an expression Or Match for Open Closing Brackets
If you appeared for coding interview round then you might have encountered this problem before. This is a pretty common question and can be solved by using Stack Data Structure
Solution in C#
public void OpenClosingBracketsMatch()
{
string pattern = "{[(((((}}])";
Dictionary<char, char> matchLookup = new Dictionary<char, char>();
matchLookup['{'] = '}';
matchLookup['('] = ')';
matchLookup['['] = ']';
Stack<char> stck = new Stack<char>();
for (int i = 0; i < pattern.Length; i++)
{
char currentChar = pattern[i];
if (matchLookup.ContainsKey(currentChar))
stck.Push(currentChar);
else if (currentChar == '}' || currentChar == ')' || currentChar == ']')
{
char topCharFromStack = stck.Peek();
if (matchLookup[topCharFromStack] != currentChar)
{
Console.WriteLine("NOT Matched");
return;
}
}
}
Console.WriteLine("Matched");
}
For more information, you may also refer to this link: https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
here is my solution using c++
if brackets are matched then returns true if not then gives false
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
int matchbracket(string expr){
stack<char> st;
int i;
char x;
for(i=0;i<expr.length();i++){
if(expr[i]=='('||expr[i]=='{'||expr[i]=='[')
st.push(expr[i]);
if(st.empty())
return -1;
switch(expr[i]){
case ')' :
x=expr[i];
st.pop();
if(x=='}'||x==']')
return 0;
break;
case '}' :
x=expr[i];
st.pop();
if(x==')'||x==']')
return 0;
break;
case ']' :
x=expr[i];
st.pop();
if(x==')'||x=='}')
return 1;
break;
}
}
return(st.empty());
}
int main()
{
string expr;
cin>>expr;
if(matchbracket(expr)==1)
cout<<"\nTRUE\n";
else
cout<<"\nFALSE\n";
}
This is my implementation for this problem:
public class BalancedBrackets {
static final Set<Character> startBrackets = Set.of('(', '[', '{');
static final Map<Character, Character> bracketsMap = Map.of('(', ')', '[', ']', '{', '}');
public static void main(String[] args) {
// Here you can add test cases
Arrays.asList(
"(())",
"([])",
"()()(())({})"
).forEach(expTest -> System.out.printf("%s is %s balanced%n", expTest, isBalancedBrackets(expTest) ? "" : "not"));
}
public static boolean isBalancedBrackets(String exp) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < exp.length(); i++) {
Character chr = exp.charAt(i);
if (bracketsMap.containsKey(chr)) {
stack.push(chr);
continue;
}
if (stack.isEmpty()) {
return false;
}
Character check = stack.pop();
if (bracketsMap.get(check) != chr) {
return false;
}
}
return (stack.isEmpty());
}
}
https://github.com/CMohamed/ProblemSolving/blob/main/other/balanced-brackets/BalancedBrackets.java
//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))->
//Split string to substring {[()]}, next [], next [], next{}
public class testbrackets {
static String stringfirst;
static String stringsecond;
static int open = 0;
public static void main(String[] args) {
splitstring("(()){}()");
}
static void splitstring(String str){
int len = str.length();
for(int i=0;i<=len-1;i++){
stringfirst="";
stringsecond="";
System.out.println("loop starttttttt");
char a = str.charAt(i);
if(a=='{'||a=='['||a=='(')
{
open = open+1;
continue;
}
if(a=='}'||a==']'||a==')'){
if(open==0){
System.out.println(open+"started with closing brace");
return;
}
String stringfirst=str.substring(i-open, i);
System.out.println("stringfirst"+stringfirst);
String stringsecond=str.substring(i, i+open);
System.out.println("stringsecond"+stringsecond);
replace(stringfirst, stringsecond);
}
i=(i+open)-1;
open=0;
System.out.println(i);
}
}
static void replace(String stringfirst, String stringsecond){
stringfirst = stringfirst.replace('{', '}');
stringfirst = stringfirst.replace('(', ')');
stringfirst = stringfirst.replace('[', ']');
StringBuilder stringfirst1 = new StringBuilder(stringfirst);
stringfirst = stringfirst1.reverse().toString();
System.out.println("stringfirst"+stringfirst);
System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
System.out.println("pass");
}
else{
System.out.println("fail");
System.exit(0);
}
}
}
import java.util.Stack;
class Demo
{
char c;
public boolean checkParan(String word)
{
Stack<Character> sta = new Stack<Character>();
for(int i=0;i<word.length();i++)
{
c=word.charAt(i);
if(c=='(')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c=='{')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c==')')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='(')
{
sta.pop();
System.out.println(" ) is poped from the Stack");
}
else if(sta.peek()=='(' && sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
}
else if(c=='}')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='{')
{
sta.pop();
System.out.println(" } is poped from the Stack");
}
}
else if(c=='(')
{
if(sta.empty())
{
System.out.println("Stack is empty only ( parenthesis in Stack ");
}
}
}
// System.out.print("The top element is : "+sta.peek());
return sta.empty();
}
}
public class ParaenthesisChehck {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Demo d1= new Demo();
// d1.checkParan(" ");
// d1.checkParan("{}");
//d1.checkParan("()");
//d1.checkParan("{()}");
// d1.checkParan("{123}");
d1.checkParan("{{{}}");
}
}
import java.util.*;
public class Parenthesis
{
public static void main(String...okok)
{
Scanner sc= new Scanner(System.in);
String str=sc.next();
System.out.println(isValid(str));
}
public static int isValid(String a) {
if(a.length()%2!=0)
{
return 0;
}
else if(a.length()==0)
{
return 1;
}
else
{
char c[]=a.toCharArray();
Stack<Character> stk = new Stack<Character>();
for(int i=0;i<c.length;i++)
{
if(c[i]=='(' || c[i]=='[' || c[i]=='{')
{
stk.push(c[i]);
}
else
{
if(stk.isEmpty())
{
return 0;
//break;
}
else
{
char cc=c[i];
if(cc==')' && stk.peek()=='(' )
{
stk.pop();
}
else if(cc==']' && stk.peek()=='[' )
{
stk.pop();
}
else if(cc=='}' && stk.peek()=='{' )
{
stk.pop();
}
}
}
}
if(stk.isEmpty())
{
return 1;
}else
{
return 0;
}
}
}
}
I tried this using javascript below is the result.
function bracesChecker(str) {
if(!str) {
return true;
}
var openingBraces = ['{', '[', '('];
var closingBraces = ['}', ']', ')'];
var stack = [];
var openIndex;
var closeIndex;
//check for opening Braces in the val
for (var i = 0, len = str.length; i < len; i++) {
openIndex = openingBraces.indexOf(str[i]);
closeIndex = closingBraces.indexOf(str[i]);
if(openIndex !== -1) {
stack.push(str[i]);
}
if(closeIndex !== -1) {
if(openingBraces[closeIndex] === stack[stack.length-1]) {
stack.pop();
} else {
return false;
}
}
}
if(stack.length === 0) {
return true;
} else {
return false;
}
}
var testStrings = [
'',
'test',
'{{[][]()()}()}[]()',
'{test{[test]}}',
'{test{[test]}',
'{test{(yo)[test]}}',
'test{[test]}}',
'te()s[]t{[test]}',
'te()s[]t{[test'
];
testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));
import java.util.*;
public class MatchBrackets {
public static void main(String[] argh) {
String input = "[]{[]()}";
System.out.println (input);
char [] openChars = {'[','{','('};
char [] closeChars = {']','}',')'};
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
String x = "" +input.charAt(i);
if (String.valueOf(openChars).indexOf(x) != -1)
{
stack.push(input.charAt(i));
}
else
{
Character lastOpener = stack.peek();
int idx1 = String.valueOf(openChars).indexOf(lastOpener.toString());
int idx2 = String.valueOf(closeChars).indexOf(x);
if (idx1 != idx2)
{
System.out.println("false");
return;
}
else
{
stack.pop();
}
}
}
if (stack.size() == 0)
System.out.println("true");
else
System.out.println("false");
}
}
If you want to have a look at my code. Just for reference
public class Default {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfString = Integer.parseInt(br.readLine());
String s;
String stringBalanced = "YES";
Stack<Character> exprStack = new Stack<Character>();
while ((s = br.readLine()) != null) {
stringBalanced = "YES";
int length = s.length() - 1;
for (int i = 0; i <= length; i++) {
char tmp = s.charAt(i);
if(tmp=='[' || tmp=='{' || tmp=='('){
exprStack.push(tmp);
}else if(tmp==']' || tmp=='}' || tmp==')'){
if(!exprStack.isEmpty()){
char peekElement = exprStack.peek();
exprStack.pop();
if(tmp==']' && peekElement!='['){
stringBalanced="NO";
}else if(tmp=='}' && peekElement!='{'){
stringBalanced="NO";
}else if(tmp==')' && peekElement!='('){
stringBalanced="NO";
}
}else{
stringBalanced="NO";
break;
}
}
}
if(!exprStack.isEmpty()){
stringBalanced = "NO";
}
exprStack.clear();
System.out.println(stringBalanced);
}
}
}
public static bool IsBalanced(string input)
{
Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
{ '<', '>' }
};
Stack<char> brackets = new Stack<char>();
try
{
// Iterate through each character in the input string
foreach (char c in input)
{
// check if the character is one of the 'opening' brackets
if (bracketPairs.Keys.Contains(c))
{
// if yes, push to stack
brackets.Push(c);
}
else
// check if the character is one of the 'closing' brackets
if (bracketPairs.Values.Contains(c))
{
// check if the closing bracket matches the 'latest' 'opening' bracket
if (c == bracketPairs[brackets.First()])
{
brackets.Pop();
}
else
// if not, its an unbalanced string
return false;
}
else
// continue looking
continue;
}
}
catch
{
// an exception will be caught in case a closing bracket is found,
// before any opening bracket.
// that implies, the string is not balanced. Return false
return false;
}
// Ensure all brackets are closed
return brackets.Count() == 0 ? true : false;
}
public String checkString(String value) {
Stack<Character> stack = new Stack<>();
char topStackChar = 0;
for (int i = 0; i < value.length(); i++) {
if (!stack.isEmpty()) {
topStackChar = stack.peek();
}
stack.push(value.charAt(i));
if (!stack.isEmpty() && stack.size() > 1) {
if ((topStackChar == '[' && stack.peek() == ']') ||
(topStackChar == '{' && stack.peek() == '}') ||
(topStackChar == '(' && stack.peek() == ')')) {
stack.pop();
stack.pop();
}
}
}
return stack.isEmpty() ? "YES" : "NO";
}
Here's a solution in Python.
#!/usr/bin/env python
def brackets_match(brackets):
stack = []
for char in brackets:
if char == "{" or char == "(" or char == "[":
stack.append(char)
if char == "}":
if stack[-1] == "{":
stack.pop()
else:
return False
elif char == "]":
if stack[-1] == "[":
stack.pop()
else:
return False
elif char == ")":
if stack[-1] == "(":
stack.pop()
else:
return False
if len(stack) == 0:
return True
else:
return False
if __name__ == "__main__":
print(brackets_match("This is testing {([])} if brackets have match."))
Was asked to implement this algorithm at live coding interview, here's my refactored solution in C#:
Git Tests
package com.balance.braces;
import java.util.Arrays;
import java.util.Stack;
public class BalanceBraces {
public static void main(String[] args) {
String[] values = { "()]", "[()]" };
String[] rsult = match(values);
Arrays.stream(rsult).forEach(str -> System.out.println(str));
}
static String[] match(String[] values) {
String[] returnString = new String[values.length];
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value.length() % 2 != 0) {
returnString[i] = "NO";
continue;
} else {
Stack<Character> buffer = new Stack<Character>();
for (char ch : value.toCharArray()) {
if (buffer.isEmpty()) {
buffer.add(ch);
} else {
if (isMatchedBrace(buffer.peek(), ch)) {
buffer.pop();
} else {
buffer.push(ch);
}
}
if (buffer.isEmpty()) {
returnString[i] = "YES";
} else {
returnString[i] = "FALSE";
}
}
}
}
return returnString;
}
static boolean isMatchedBrace(char start, char endmatch) {
if (start == '{')
return endmatch == '}';
if (start == '(')
return endmatch == ')';
if (start == '[')
return endmatch == ']';
return false;
}
}
in java you don't want to compare the string or char by == signs. you would use equals method. equalsIgnoreCase or something of the like. if you use == it must point to the same memory location. In the method below I attempted to use ints to get around this. using ints here from the string index since every opening brace has a closing brace. I wanted to use location match instead of a comparison match. But i think with this you have to be intentional in where you place the characters of the string. Lets also consider that Yes = true and No = false for simplicity. This answer assumes that you passed an array of strings to inspect and required an array of if yes (they matched) or No (they didn't)
import java.util.Stack;
public static void main(String[] args) {
//String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","{}","}]{}","{[)]()}"};
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{([)]}" is _not_ balanced
String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","()[]{}","}]{}","{[)]()}","{[)]()}","{([)]}"};
String[] answers = new String[arrayOfBraces.length];
String openers = "([{";
String closers = ")]}";
String stringToInspect = "";
Stack<String> stack = new Stack<String>();
for (int i = 0; i < arrayOfBraces.length; i++) {
stringToInspect = arrayOfBraces[i];
for (int j = 0; j < stringToInspect.length(); j++) {
if(stack.isEmpty()){
if (openers.indexOf(stringToInspect.charAt(j))>=0) {
stack.push(""+stringToInspect.charAt(j));
}
else{
answers[i]= "NO";
j=stringToInspect.length();
}
}
else if(openers.indexOf(stringToInspect.charAt(j))>=0){
stack.push(""+stringToInspect.charAt(j));
}
else{
String comparator = stack.pop();
int compLoc = openers.indexOf(comparator);
int thisLoc = closers.indexOf(stringToInspect.charAt(j));
if (compLoc != thisLoc) {
answers[i]= "NO";
j=stringToInspect.length();
}
else{
if(stack.empty() && (j== stringToInspect.length()-1)){
answers[i]= "YES";
}
}
}
}
}
System.out.println(answers.length);
for (int j = 0; j < answers.length; j++) {
System.out.println(answers[j]);
}
}
Check balanced parenthesis or brackets with stack--
var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
var stk = [];
function bracket_balance(){
for(var i=0;i<excp.length;i++){
if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
stk.push(excp[i]);
}else if(excp[i]== ']' && stk.pop() != '['){
return false;
}else if(excp[i]== '}' && stk.pop() != '{'){
return false;
}else if(excp[i]== ')' && stk.pop() != '('){
return false;
}
}
return true;
}
console.log(bracket_balance());
//Parenthesis are balance then return true else false

Categories

Resources