-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b308375
commit fc97d90
Showing
4 changed files
with
87 additions
and
1 deletion.
There are no files selected for viewing
73 changes: 73 additions & 0 deletions
73
Java/Data-Structures/STACKS/MISC-STACKS/BracketsBalancedOrNot.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,73 @@ | ||
import java.util.*; | ||
public class BracketsBalancedOrNot | ||
{ | ||
public static void main(String[] args) | ||
{ | ||
Scanner in = new Scanner(System.in); | ||
String expression = in.nextLine(); | ||
in.close(); | ||
if(BalancedOrNot(expression)) | ||
{ | ||
System.out.println("BRACKET BALANCED"); | ||
} | ||
else | ||
{ | ||
System.out.println("BRACKET NOT BALANCED"); | ||
} | ||
} | ||
private static char reverseBracket(char ch) | ||
{ | ||
switch(ch) | ||
{ | ||
case ')': | ||
return '('; | ||
case ']': | ||
return '['; | ||
case '}': | ||
return '{'; | ||
default: | ||
return '0'; | ||
} | ||
} | ||
//this method will throw empty stack exception | ||
private static boolean BalancedOrNot(String expression) throws EmptyStackException | ||
{ | ||
Stack<Character> S = new Stack<Character>(); | ||
try | ||
{ | ||
for(int i=0;i<expression.length();i++) | ||
{ | ||
char ch = expression.charAt(i); | ||
if(ch=='(' || ch=='[' || ch=='{') | ||
{ | ||
S.push(ch); | ||
} | ||
else if(ch==')' || ch==']' || ch=='}') | ||
{ | ||
char rev = reverseBracket(ch); | ||
if(S.empty()) | ||
{ | ||
throw new EmptyStackException(); | ||
} | ||
if(rev == S.peek()) | ||
{ | ||
S.pop(); | ||
} | ||
else | ||
{ | ||
return false; | ||
} | ||
} | ||
} | ||
if(S.empty()) | ||
{ | ||
return true; | ||
} | ||
} | ||
catch(Exception e) | ||
{ | ||
System.out.println("STACK IS EMPTY"); | ||
} | ||
return false; | ||
} | ||
} |
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
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
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