-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2102 from jigyasabisht/patch-2
Create Balancedbrackets.java
- Loading branch information
Showing
1 changed file
with
87 additions
and
0 deletions.
There are no files selected for viewing
87 changes: 87 additions & 0 deletions
87
Program's_Contributed_By_Contributors/Java_Programs/Data_structure/Balancedbrackets.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
/* | ||
Question : Balanced Brackets | ||
1. You are given a string exp representing an expression. | ||
2. You are required to check if the expression is balanced i.e. closing brackets and opening brackets match up well. | ||
e.g. | ||
[(a + b) + {(c + d) * (e / f)}] -> true | ||
[(a + b) + {(c + d) * (e / f)]} -> false | ||
[(a + b) + {(c + d) * (e / f)} -> false | ||
([(a + b) + {(c + d) * (e / f)}] -> false | ||
*/ | ||
|
||
//Code | ||
import java.io.*; | ||
import java.util.*; | ||
public class Balancedbrackets | ||
{ | ||
public static void main(String[] args) | ||
{ | ||
Scanner sc = new Scanner(System.in); | ||
String str = sc.nextLine(); | ||
Stack<Character> st = new Stack<>(); | ||
for(int i=0;i<str.length();i++) | ||
{ | ||
char ch = str.charAt(i); | ||
if(ch == '(' || ch == '[' || ch=='{') | ||
{ | ||
st.push(ch); | ||
} | ||
else if(ch==')') | ||
{ | ||
boolean val = handleClossing(st, '('); | ||
if(val==false) | ||
{ | ||
System.out.println(val); | ||
return; | ||
} | ||
} | ||
else if(ch=='}') | ||
{ | ||
boolean val = handleClossing(st, '{'); | ||
if(val==false) | ||
{ | ||
System.out.println(val); | ||
return; | ||
} | ||
} | ||
else if(ch==']') | ||
{ | ||
boolean val = handleClossing(st, '['); | ||
if(val==false) | ||
{ | ||
System.out.println(val); | ||
return; | ||
} | ||
} | ||
else{ | ||
|
||
} | ||
} | ||
if(st.size() == 0) | ||
{ | ||
System.out.println(true); | ||
} | ||
else{ | ||
System.out.println(false); | ||
} | ||
} | ||
public static boolean handleClossing(Stack<Character>st, char corresoch) | ||
{ | ||
if(st.size() == 0) | ||
{ | ||
return false; | ||
} | ||
else if(st.peek() != corresoch) | ||
{ | ||
return false; | ||
} | ||
else{ | ||
st.pop(); | ||
return true; | ||
} | ||
} | ||
} |