Related
can someone help me with this code it is not working with this test case{(([])[])[]]}.
package myProject;
import java.util.*;
public class bracketBalancing {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s=sc.next();
Stack<Character> stack=new Stack<Character>();
if(s.length()==0)
System.out.println("string is empty");
else {
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch=='('||ch=='{'||ch=='['){
stack.push(ch);
}
else if(ch==')'&& stack.peek()=='('){
stack.pop();
}
else if(ch=='}'&& stack.peek()=='{'){
stack.pop();
}
else if(ch==']'&& stack.peek()=='['){
stack.pop();
}
}
}
if(stack.empty()){
System.out.println("YES");
}
else{
System.out.println("No");
}
sc.close();
}
}
You should add the else condition to print No if you are neither able to push not pop. Because in that condition it means you have some additional closing brackets which will lead to unbalanced.
Code:
if (s.length() == 0) {
System.out.println("string is empty");
} else {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' && stack.peek() == '(') {
stack.pop();
} else if (ch == '}' && stack.peek() == '{') {
stack.pop();
} else if (ch == ']' && stack.peek() == '[') {
stack.pop();
} else {
System.out.println("No");
stack = null;
break;
}
}
}
if(stack != null) {
if (stack.empty()) {
System.out.println("YES");
} else {
System.out.println("No");
}
}
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.
I have a problem with my code , can you help me please with this ..
I want to make a recursion Matching brackets reading from txt ..
this is my class , so i need help with the code if possible ,, thanks too much
import java.util.*;
import java.io.*;
public class MatchBrackets
{
public static void main(String [] args) throws FileNotFoundException
{
boolean answer;
String st;
Scanner infile = new Scanner (new FileReader("MatchExpression.txt"));
PrintWriter outFile = new PrintWriter ("MatchResults.txt");
while (infile.hasNext())
{
st = infile.nextLine();
outFile.println("Expression #" + ": " + st);
answer = matchBrackets(st);
if(answer == true)
outFile.println( " Invalid Expression \n");
else
outFile.println( " The value of this expression is: "
+ answer);
outFile.println(); outFile.println();
}
infile.close();
outFile.close();
}
public static boolean matchBrackets (String str)
{
ArrayStack S = new ArrayStack(100);
char ch;
if ((str == null) || str.isEmpty()) {
return str.isEmpty();
}
else {
ch=str.charAt(0);
if(ch=='{' || ch=='(' ||ch=='[' )
{ S.push(ch); }
else if (ch=='}' || ch==')' ||ch==']' ){
if(S.isEmpty())
return false;
switch(S.pop()){
case '{': if(ch!='}') return false; break;
case '[': if(ch!=']') return false; break;
case '(': if(ch!=')') return false; break;
}
}
return matchBrackets(str);
}
}
}
And the ArrayStack , included POP , PUSH , isEmpty ... etc
So here's the problem, each recursive call you do:
ArrayStack S = new ArrayStack(100);
which means that each call you create a totally new stack. So you may want to create a new stack for each line you read from file and just pass this stack to your function.
Here is my solution. I assumed some dummy test strings instead of reading from file, it's basically the same thing. Just to test the function.
public class Main {
public static void main(String[] args) {
// test string
String [] tests = {"[][][]{}()", ")(()){([()])}", "((()(()){([()])}", "({[]}){[]}()"};
for (int i =0; i < 4; i++) {
Stack<Character> stack = new Stack<>();
System.out.println(matchBrackets(stack, tests[i], 0));
}
}
private static boolean matchBrackets(Stack<Character> stack, String str, int i) {
// if we reached the end of the string, then check if stack is empty or not
if (i == str.length() && !stack.isEmpty()) return false;
else if (i == str.length() && stack.isEmpty()) return true;
if (str.charAt(i) == '(' || str.charAt(i) == '{' || str.charAt(i) == '['){
stack.push(str.charAt(i));
return matchBrackets(stack,str,++i);
} else {
// if stack is empty, then the expression is false
if (stack.isEmpty()) return false;
char c = stack.pop();
if ( (str.charAt(i) == '}' && c != '{') && (str.charAt(i) == ']' && c != '[') && (str.charAt(i) == ')' && c != '(') ) {
return false;
} else {
return matchBrackets(stack,str,++i);
}
}
}
}
Note: You can actually for example clear the stack for every expression instead of re-initializing it.
I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.
I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.
Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
I hope this code can help:
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
System.out.println(balancedParenthensies("{(a,b)}"));
System.out.println(balancedParenthensies("{(a},b)"));
System.out.println(balancedParenthensies("{)(a,b}"));
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
public static boolean isBalanced(String expression) {
if ((expression.length() % 2) == 1) return false;
else {
Stack<Character> s = new Stack<>();
for (char bracket : expression.toCharArray())
switch (bracket) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
default :
if (s.isEmpty() || bracket != s.peek()) { return false;}
s.pop();
}
return s.isEmpty();
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String expression = in.nextLine();
boolean answer = isBalanced(expression);
if (answer) { System.out.println("YES");}
else { System.out.println("NO");}
}
The pseudo code equivalent java implementation of the algorithm is java is as follows.
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* #author Yogen Rai
*/
public class BalancedBraces
{
public static void main(String[] args) {
System.out.println(isBalanced("{{}}") ? "YES" : "NO"); // YES
System.out.println(isBalanced("{{}(") ? "YES" : "NO"); // NO
System.out.println(isBalanced("{()}") ? "YES" : "NO"); // YES
System.out.println(isBalanced("}{{}}") ? "YES" : "NO"); // NO
}
public static boolean isBalanced(String brackets) {
// set matching pairs
Map<Character, Character> braces = new HashMap<>();
braces.put('(', ')');
braces.put('[',']');
braces.put('{','}');
// if length of string is odd, then it is not balanced
if (brackets.length() % 2 != 0) {
return false;
}
// travel half until openings are found and compare with
// remaining if the closings matches
Stack<Character> halfBraces = new Stack();
for(char ch: brackets.toCharArray()) {
if (braces.containsKey(ch)) {
halfBraces.push(braces.get(ch));
}
// if stack is empty or if closing bracket is not equal to top of stack,
// then braces are not balanced
else if(halfBraces.isEmpty() || ch != halfBraces.pop()) {
return false;
}
}
return halfBraces.isEmpty();
}
}
It's important to use a stack to push opening symbols onto it, then when you come across a closing brace you pop the element off the top of the stack and then you check it to see if it matches the type of closing brace. Here is a java implementation.
import java.util.Stack;
public class Balanced {
public static void main (String [] args)
{
String test_good = "()(){}{}{()}";
String test_bad = "((({}{}))()";
System.out.println(checkBalanced(test_good));
System.out.println(checkBalanced(test_bad));
}
public static boolean checkBalanced(String check)
{
Stack<Character> S = new Stack<Character>();
for(int a = 0; a < check.length(); a++)
{
char let = check.charAt(a);
if(let == '[' || let == '{' || let == '(')
S.push(let);
else if(let == ']' || let == '}' || let == ')')
{
if(S.empty())
return false;
switch(let)
{
// Opening square brace
case ']':
if (S.pop() != '[')
return false;
break;
// Opening curly brace
case '}':
if (S.pop() != '{')
return false;
break;
// Opening paren brace
case ')':
if (S.pop() != '(')
return false;
break;
default:
break;
}
}
}
if(S.empty())
return true;
return false;
}
}
Do you mind, if I will add my freaky-style solution based on JavaScript?
It's an ad-hoc stuff, not for production, but for the interviews or something like that. Or just for fun.
The code:
function reduceStr (str) {
const newStr = str.replace('()', '').replace('{}', '').replace('[]', '')
if (newStr !== str) return reduceStr(newStr)
return newStr
}
function verifyNesting (str) {
return reduceStr(str).length === 0
}
Checks:
console.log(verifyNesting('[{{[(){}]}}[]{}{{(())}}]')) //correct
console.log(verifyNesting('[{{[(){}]}}[]{}{({())}}]')) //incorrect
Explanation:
It will recursively remove closes pairs "()", "[]" and "{}":
'[{{[(){}]}}[]{}{{(())}}]'
'[{{}}[]{}{{(())}}]'
'[{}{}{{()}}]'
'[{}{{}}]'
'[{{}}]'
'[{}]'
''
If at the end string's length will be empty - it's true, if not - it's false.
P.S. Few answers
Why not for production?
Because it's slow, and don't care about the possibility of some other characters between pairs.
Why JS? We love Java
Because I'm a frontend developer but met the same task, so perhaps it can be useful for somebody. And JS is also JVM lang =)
But why...
Because all JS developers are crazy, that's why.
This is my own implementation. I tried to make it the shortest an clearest way possible:
public static boolean isBraceBalanced(String braces) {
Stack<Character> stack = new Stack<Character>();
for(char c : braces.toCharArray()) {
if(c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if((c == ')' && (stack.isEmpty() || stack.pop() != '(')) ||
(c == ']' && (stack.isEmpty() || stack.pop() != '[')) ||
(c == '}' && (stack.isEmpty() || stack.pop() != '{'))) {
return false;
}
}
return stack.isEmpty();
}
You are pushing i - the index - on the stack, and comparing against ch. You should push and pop ch.
Please try this.
import java.util.Stack;
public class PatternMatcher {
static String[] patterns = { "{([])}", "{}[]()", "(}{}]]", "{()", "{}" };
static String openItems = "{([";
boolean isOpen(String sy) {
return openItems.contains(sy);
}
String getOpenSymbol(String byCloseSymbol) {
switch (byCloseSymbol) {
case "}":
return "{";
case "]":
return "[";
case ")":
return "(";
default:
return null;
}
}
boolean isValid(String pattern) {
if(pattern == null) {
return false;
}
Stack<String> stack = new Stack<String>();
char[] symbols = pattern.toCharArray();
if (symbols.length == 0 || symbols.length % 2 != 0) {
return false;
}
for (char c : symbols) {
String symbol = Character.toString(c);
if (isOpen(symbol)) {
stack.push(symbol);
} else {
String openSymbol = getOpenSymbol(symbol);
if (stack.isEmpty()
|| openSymbol == null
|| !openSymbol.equals(stack.pop())) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
PatternMatcher patternMatcher = new PatternMatcher();
for (String pattern : patterns) {
boolean valid = patternMatcher.isValid(pattern);
System.out.println(pattern + "\t" + valid);
}
}
}
Using switch-case for better readability and handling of other scenarios:
import java.util.Scanner;
import java.util.Stack;
public class JavaStack
{
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
System.out.println(isStringBalanced(input));
}
scanner.close();
}
private static boolean isStringBalanced(String testString)
{
Stack<Character> stack = new Stack<Character>();
for (char c : testString.toCharArray()) {
switch (c) {
case '[':
case '(':
case '{':
stack.push(c);
break;
case ']':
if (stack.isEmpty() || stack.pop() != '[') {
return false;
}
break;
case ')':
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
break;
case '}':
if (stack.isEmpty() || stack.pop() != '{') {
return false;
}
break;
default:
break;
}
}
// stack has to be empty, if not, the balance was wrong
return stack.empty();
}
}
This is my implementation for this question. This program allows numbers, alphabets and special characters with input string but simply ignore them while processing the string.
CODE:
import java.util.Scanner;
import java.util.Stack;
public class StringCheck {
public static void main(String[] args) {
boolean flag =false;
Stack<Character> input = new Stack<Character>();
System.out.println("Enter your String to check:");
Scanner scanner = new Scanner(System.in);
String sinput = scanner.nextLine();
char[] c = new char[15];
c = sinput.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '{' || c[i] == '(' || c[i] == '[')
input.push(c[i]);
else if (c[i] == ']') {
if (input.pop() == '[') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == ')') {
if (input.pop() == '(') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == '}') {
if (input.pop() == '{') {
flag = true;
continue;
} else {
flag = false;
break;
}
}
}
if (flag == true)
System.out.println("Valid String");
else
System.out.println("Invalid String");
scanner.close();
}
}
Similar to one of the code above in JAVA but It needs one more else statement added in order to avoid stack comparison with characters other than braces :
else if(bracketPair.containsValue(strExpression.charAt(i)))
public boolean isBalanced(String strExpression){
Map<Character,Character> bracketPair = new HashMap<Character,Character>();
bracketPair.put('(', ')');
bracketPair.put('[', ']');
bracketPair.put('{', '}');
Stack<Character> stk = new Stack<Character>();
for(int i =0;i<strExpression.length();i++){
if(bracketPair.containsKey(strExpression.charAt(i)))
stk.push(strExpression.charAt(i));
else if(bracketPair.containsValue(strExpression.charAt(i)))
if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
return false;
}
if(stk.isEmpty())
return true;
else
return false;
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthesisWithStack {
/*This is purely Java Stack based solutions without using additonal
data structure like array/Map */
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
/*Take list of String inputs (parenthesis expressions both valid and
invalid from console*/
List<String> inputs=new ArrayList<>();
while (sc.hasNext()) {
String input=sc.next();
inputs.add(input);
}
//For every input in above list display whether it is valid or
//invalid parenthesis expression
for(String input:inputs){
System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
(input));
}
}
//This method identifies whether expression is valid parenthesis or not
public static boolean isBalancedParenthesis(String expression){
//sequence of opening parenthesis according to its precedence
//i.e. '[' has higher precedence than '{' or '('
String openingParenthesis="[{(";
//sequence of closing parenthesis according to its precedence
String closingParenthesis=")}]";
//Stack will be pushed on opening parenthesis and popped on closing.
Stack<Character> parenthesisStack=new Stack<>();
/*For expression to be valid :
CHECK :
1. it must start with opening parenthesis [()...
2. precedence of parenthesis should be proper (eg. "{[" invalid
"[{(" valid )
3. matching pair if( '(' => ')') i.e. [{()}(())] ->valid [{)]not
*/
if(closingParenthesis.contains
(((Character)expression.charAt(0)).toString())){
return false;
}else{
for(int i=0;i<expression.length();i++){
char ch= (Character)expression.charAt(i);
//if parenthesis is opening(ie any of '[','{','(') push on stack
if(openingParenthesis.contains(ch.toString())){
parenthesisStack.push(ch);
}else if(closingParenthesis.contains(ch.toString())){
//if parenthesis is closing (ie any of ']','}',')') pop stack
//depending upon check-3
if(parenthesisStack.peek()=='(' && (ch==')') ||
parenthesisStack.peek()=='{' && (ch=='}') ||
parenthesisStack.peek()=='[' && (ch==']')
){
parenthesisStack.pop();
}
}
}
return (parenthesisStack.isEmpty())? true : false;
}
}
An alternative to Hashmap and an efficient way would be to use a Deque:
public boolean isValid(String s)
{
if(s == null || s.length() == 0)
return true;
Deque<Character> stack = new ArrayDeque<Character>();
for(char c : s.toCharArray())
{
if(c == '{')
stack.addFirst('}');
else if(c == '(')
stack.addFirst(')');
else if(c == '[')
stack .addFirst(']');
else if(stack.isEmpty() || c != stack.removeFirst())
return false;
}
return stack.isEmpty();
}
Late Post.
package com.prac.stack;
public class BalanceBrackets {
public static void main(String[] args) {
String str = "{()}[]";
char a[] = str.toCharArray();
System.out.println(check(a));
}
static boolean check(char[] t) {
Stackk st = new Stackk();
for (int i = 0; i < t.length; i++) {
if (t[i] == '{' || t[i] == '(' || t[i] == '[') {
st.push(t[i]);
}
if (t[i] == '}' || t[i] == ')' || t[i] == ']') {
if (st.isEmpty()) {
return false;
} else if (!isMatching(st.pop(), t[i])) {
return false;
}
}
}
if (st.isEmpty()) {
return true;
} else {
return false;
}
}
static boolean isMatching(char a, char b) {
if (a == '(' && b == ')') {
return true;
} else if (a == '{' && b == '}') {
return true;
} else if (a == '[' && b == ']') {
return true;
} else {
return false;
}
}
}
public static void main(String[] args) {
String exp = "{[()()]()}";
if(isBalanced(exp)){
System.out.println("Balanced");
}else{
System.out.println("Not Balanced");
}
}
public static boolean isBalanced(String exp){
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < exp.length(); i++) {
char a = exp.charAt(i);
char b =' ';
if(!stack.isEmpty()){
b = stack.peek();
}
if(a == '(' || a == '[' || a == '{'){
stack.push(a);
continue;
}
else if((b == '(' && a == ')') || (b == '[' && a == ']') || (b == '{' && a == '}')){
stack.pop();
continue;
}
else{
return false;
}
}
return stack.isEmpty();
}
Stack is always most preferable data structure in this case, you can try this by considering time and space complexity.
This code works for all cases include other chars not only parentheses
ex:
Please enter input
{ibrahim[k]}
true
()[]{}[][]
true
saddsd]
false
public class Solution {
private static Map<Character, Character> parenthesesMapLeft = new HashMap<>();
private static Map<Character, Character> parenthesesMapRight = new HashMap<>();
static {
parenthesesMapLeft.put('(', '(');
parenthesesMapRight.put(')', '(');
parenthesesMapLeft.put('[', '[');
parenthesesMapRight.put(']', '[');
parenthesesMapLeft.put('{', '{');
parenthesesMapRight.put('}', '{');
}
public static void main(String[] args) {
System.out.println("Please enter input");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
System.out.println(isBalanced(str));
}
public static boolean isBalanced(String str) {
boolean result = false;
if (str.length() < 2)
return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!parenthesesMapRight.containsKey(ch) && !parenthesesMapLeft.containsKey(ch)) {
continue;
}
if (parenthesesMapLeft.containsKey(ch)) {
stack.push(ch);
} else {
if (!stack.isEmpty() && stack.pop() == parenthesesMapRight.get(ch).charValue()) {
result = true;
} else {
return false;
}
}
}
if (!stack.isEmpty())
return result = false;
return result;
}
}
import java.util.Stack;
public class StackParenthesisImplementation {
public static void main(String[] args) {
String Parenthesis = "[({})]";
char[] charParenthesis = Parenthesis.toCharArray();
boolean evalParanthesisValue = evalParanthesis(charParenthesis);
if(evalParanthesisValue == true)
System.out.println("Brackets are good");
else
System.out.println("Brackets are not good");
}
static boolean evalParanthesis(char[] brackets)
{
boolean IsBracesOk = false;
boolean PairCount = false;
Stack<Character> stack = new Stack<Character>();
for(char brace : brackets)
{
if(brace == '(' || brace == '{' || brace == '['){
stack.push(brace);
PairCount = false;
}
else if(!stack.isEmpty())
{
if(brace == ')' || brace == '}' || brace == ']')
{
char CharPop = stack.pop();
if((brace == ')' && CharPop == '('))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == '}') && (CharPop == '{'))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == ']') && (CharPop == '['))
{
IsBracesOk = true; PairCount = true;
}
else
{
IsBracesOk = false;
PairCount = false;
break;
}
}
}
}
if(PairCount == false)
return IsBracesOk = false;
else
return IsBracesOk = true;
}
}
public static void main(String[] args) {
System.out.println("is balanced : "+isBalanced("(){}[]<>"));
System.out.println("is balanced : "+isBalanced("({})[]<>"));
System.out.println("is balanced : "+isBalanced("({[]})<>"));
System.out.println("is balanced : "+isBalanced("({[<>]})"));
System.out.println("is balanced : "+isBalanced("({})[<>]"));
System.out.println("is balanced : "+isBalanced("({[}])[<>]"));
System.out.println("is balanced : "+isBalanced("([{})]"));
System.out.println("is balanced : "+isBalanced("[({}])"));
System.out.println("is balanced : "+isBalanced("[(<{>})]"));
System.out.println("is balanced : "+isBalanced("["));
System.out.println("is balanced : "+isBalanced("]"));
System.out.println("is balanced : "+isBalanced("asdlsa"));
}
private static boolean isBalanced(String brackets){
char[] bracketsArray = brackets.toCharArray();
Stack<Character> stack = new Stack<Character>();
Map<Character, Character> openingClosingMap = initOpeningClosingMap();
for (char bracket : bracketsArray) {
if(openingClosingMap.keySet().contains(bracket)){
stack.push(bracket);
}else if(openingClosingMap.values().contains(bracket)){
if(stack.isEmpty() || openingClosingMap.get(stack.pop())!=bracket){
return false;
}
}else{
System.out.println("Only < > ( ) { } [ ] brackets are allowed .");
return false;
}
}
return stack.isEmpty();
}
private static Map<Character, Character> initOpeningClosingMap() {
Map<Character, Character> openingClosingMap = new HashMap<Character, Character>();
openingClosingMap.put(Character.valueOf('('), Character.valueOf(')'));
openingClosingMap.put(Character.valueOf('{'), Character.valueOf('}'));
openingClosingMap.put(Character.valueOf('['), Character.valueOf(']'));
openingClosingMap.put(Character.valueOf('<'), Character.valueOf('>'));
return openingClosingMap;
}
Simplifying and making readable.
Using One Map only and minimum conditions to get desired result.
How about this one, it uses both concept of stack plus counter checks:
import java.util.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
Stack<Character> stk = new Stack<Character>();
char[] chr = input.toCharArray();
int ctrl = 0, ctrr = 0;
if(input.length()==0){
System.out.println("true");
}
for(int i=0; i<input.length(); i++){
if(chr[i]=='{'||chr[i]=='('||chr[i]=='['){
ctrl++;
stk.push(chr[i]);
//System.out.println(stk);
}
}
for(int i=0; i<input.length(); i++){
if(chr[i]=='}'||chr[i]==')'||chr[i]==']'){
ctrr++;
if(!stk.isEmpty())
stk.pop();
//System.out.println(stk);
}
}
//System.out.println(stk);
if(stk.isEmpty()&&ctrl==ctrr)
System.out.println("true");
else
System.out.println("false");
}
}
}
This can be used. Passes all the tests.
static String isBalanced(String s) {
if(null == s){
return "";
}
Stack<Character> bracketStack = new Stack<>();
int length = s.length();
if(length < 2 || length > 1000){
return "NO";
}
for(int i = 0; i < length; i++){
Character c= s.charAt(i);
if(c == '(' || c == '{' || c == '[' ){
bracketStack.push(c);
} else {
if(!bracketStack.isEmpty()){
char cPop = bracketStack.pop();
if(c == ']' && cPop!= '['){
return "NO";
}
if(c == ')' && cPop!= '('){
return "NO";
}
if(c == '}' && cPop!= '{'){
return "NO";
}
} else{
return "NO";
}
}
}
if(bracketStack.isEmpty()){
return "YES";
} else {
return "NO";
}
}
Please try this I checked it. It works correctly
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class CloseBrackets {
private static Map<Character, Character> leftChar = new HashMap<>();
private static Map<Character, Character> rightChar = new HashMap<>();
static {
leftChar.put('(', '(');
rightChar.put(')', '(');
leftChar.put('[', '[');
rightChar.put(']', '[');
leftChar.put('{', '{');
rightChar.put('}', '{');
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String st = bf.readLine();
System.out.println(isBalanced(st));
}
public static boolean isBalanced(String str) {
boolean result = false;
if (str.length() < 2)
return false;
Stack<Character> stack = new Stack<>();
/* For Example I gave input
* str = "{()[]}"
*/
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!rightChar.containsKey(ch) && !leftChar.containsKey(ch)) {
continue;
}
// Left bracket only add to stack. Other wise it will goes to else case
// For both above input how value added in stack
// "{(" after close bracket go to else case
if (leftChar.containsKey(ch)) {
stack.push(ch);
} else {
if (!stack.isEmpty()) {
// For both input how it performs
// 3rd character is close bracket so it will pop . pop value is "(" and map value for ")" key will "(" . So both are same .
// it will return true.
// now stack will contain only "{" , and travers to next up to end.
if (stack.pop() == rightChar.get(ch).charValue() || stack.isEmpty()) {
result = true;
} else {
return false;
}
} else {
return false;
}
}
}
if (!stack.isEmpty())
return result = false;
return result;
}
}
Using node reference we can check easily
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CloseBracketsBalance {
private static final Map<String, String> closeBracket= new HashMap<>();
private static final List<String> allBrac = new ArrayList<>();
static {
allBrac.add("[");
allBrac.add("]");
allBrac.add("{");
allBrac.add("}");
allBrac.add("(");
allBrac.add(")");
closeBracket.put("]", "[");
closeBracket.put("}", "{");
closeBracket.put(")", "(");
}
public static void main(String[] args) {
System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd)})]")); // return true
System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd}))]")); // return false
}
public static boolean checkSheetIsbalance(String c) {
char[] charArr = c.toCharArray();
Node node = null;
for(int i=0,j=charArr.length;i<j;i++) {
String ch = charArr[i]+"";
if(!allBrac.contains(ch)) {
continue;
}
if(closeBracket.containsKey(ch)) {
// node close bracket
if(node == null) {
return false;
}
if(!(node.nodeElement).equals(closeBracket.get(ch))) {
return false;
}
node = node.parent;
} else {
//make node for open bracket
node = new Node(ch, node);
}
}
if(node != null) {
return false;
}
return true;
}
}
class Node {
public String nodeElement;
public Node parent;
public Node(String el, Node p) {
this.nodeElement = el;
this.parent = p;
}
}
The improved method, from #Smartoop.
public boolean balancedParenthensies(String str) {
List<Character> leftKeys = Arrays.asList('{', '(', '<', '[');
List<Character> rightKeys = Arrays.asList('}', ')', '>', ']');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (leftKeys.contains(c)) {
stack.push(c);
} else if (rightKeys.contains(c)) {
int index = rightKeys.indexOf(c);
if (stack.isEmpty() || stack.pop() != leftKeys.get(index)) {
return false;
}
}
}
return stack.isEmpty();
}
Considering string consists only of '(' ')' '{' '}' '[' ']'. Here is a code method that returns true or false based on whether equation is balanced or not.
private static boolean checkEquation(String input) {
List<Character> charList = new ArrayList<Character>();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
charList.add(input.charAt(i));
} else if ((input.charAt(i) == ')' && charList.get(charList.size() - 1) == '(')
|| (input.charAt(i) == '}' && charList.get(charList.size() - 1) == '{')
|| (input.charAt(i) == ']' && charList.get(charList.size() - 1) == '[')) {
charList.remove(charList.size() - 1);
} else
return false;
}
if(charList.isEmpty())
return true;
else
return false;
}
///check Parenthesis
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();
}
public void validateExpression(){
if(!str.isEmpty() && str != null){
if( !str.trim().equals("(") && !str.trim().equals(")")){
char[] chars = str.toCharArray();
for(char c: chars){
if(!Character.isLetterOrDigit(c) && c == '(' || c == ')') {
charList.add(c);
}
}
for(Character ele: charList){
if(operatorMap.get(ele) != null && operatorMap.get(ele) != 0){
operatorMap.put(ele,operatorMap.get(ele)+1);
}else{
operatorMap.put(ele,1);
}
}
for(Map.Entry<Character, Integer> ele: operatorMap.entrySet()){
System.out.println(String.format("Brace Type \"%s\" and count is \"%d\" ", ele.getKey(),ele.getValue()));
}
if(operatorMap.get('(') == operatorMap.get(')')){
System.out.println("**** Valid Expression ****");
}else{
System.out.println("**** Invalid Expression ****");
}
}else{
System.out.println("**** Incomplete expression to validate ****");
}
}else{
System.out.println("**** Expression is empty or null ****");
}
}
Here is the Code. I have tested all the possible test case on Hacker Rank.
static String isBalanced(String input) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
Character ch = input.charAt(i);
if (input.charAt(i) == '{' || input.charAt(i) == '['
|| input.charAt(i) == '(') {
stack.push(input.charAt(i));
} else {
if (stack.isEmpty()
|| (stack.peek() == '[' && ch != ']')
|| (stack.peek() == '{' && ch != '}')
|| (stack.peek() == '(' && ch != ')')) {
return "NO";
} else {
stack.pop();
}
}
}
if (stack.empty())
return "YES";
return "NO";
}
import java.util.Objects;
import java.util.Stack;
public class BalanceBrackets {
public static void main(String[] args) {
String input="(a{[d]}b)";
System.out.println(isBalance(input)); ;
}
private static boolean isBalance(String input) {
Stack <Character> stackFixLength = new Stack();
if(input == null || input.length() < 2) {
throw new IllegalArgumentException("in-valid arguments");
}
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
stackFixLength.push(input.charAt(i));
}
if (input.charAt(i) == ')' || input.charAt(i) == '}' || input.charAt(i) == ']') {
if(stackFixLength.empty()) return false;
char b = stackFixLength.pop();
if (input.charAt(i) == ')' && b == '(' || input.charAt(i) == '}' && b == '{' || input.charAt(i) == ']' && b == '[') {
continue;
} else {
return false;
}
}
}
return stackFixLength.isEmpty();
}
}
package Stack;
import java.util.Stack;
public class BalancingParenthesis {
boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i)); // push to the stack
}
if (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') {
if (stack.isEmpty()) {
return false; // return false as there is nothing to match
}
Character top = stack.pop(); // to get the top element in the stack
if (top == '(' && s.charAt(i) != ')' || top == '{' && s.charAt(i) != '}'
|| top == '[' && s.charAt(i) != ']') {
return false;
}
}
}
if (stack.isEmpty()) {
return true; // check if every symbol is matched
}
return false; // if some symbols were unmatched
}
public static void main(String[] args) {
BalancingParenthesis obj = new BalancingParenthesis();
System.out.println(obj.isBalanced("()[]{}[][]"));
}
}
// Time Complexity : O(n)
Code snippet for implementing matching parenthesis using java.util.Stack data structure -
//map for storing matching parenthesis pairs
private static final Map<Character, Character> matchingParenMap = new HashMap<>();
//set for storing opening parenthesis
private static final Set<Character> openingParenSet = new HashSet<>();
static {
matchingParenMap.put(')','(');
matchingParenMap.put(']','[');
matchingParenMap.put('}','{');
openingParenSet.addAll(matchingParenMap.values());
}
//check if parenthesis match
public static boolean hasMatchingParen(String input) {
try {
//stack to store opening parenthesis
Stack<Character> parenStack = new Stack<>();
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
//if an opening parenthesis then push to the stack
if(openingParenSet.contains(ch)) {
parenStack.push(ch);
}
//for closing parenthesis
if(matchingParenMap.containsKey(ch)) {
Character lastParen = parenStack.pop();
if(lastParen != matchingParenMap.get(ch)) {
return false;
}
}
}
//returns true if the stack is empty else false
return parenStack.isEmpty();
}
catch(StackOverflowException s) {}
catch(StackUnderflowException s1) {}
return false;
}
I have explained the code snippet and the algorithm used on blog http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
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