Skip to content

Commit

Permalink
Stack Solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
shivajipotnuru committed Jun 19, 2020
1 parent 9c86a7f commit 2ba04a4
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions Stacks/Brackets Balanced.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
public class Solution {

public static boolean checkBalanced(String exp) {
// Write your code here
Stack st=new Stack();
boolean val=false;

for(int i=0;i<exp.length();i++){

if(exp.charAt(i)=='{' || exp.charAt(i)=='[' ||exp.charAt(i)=='('){
val=false;
st.push(exp.charAt(i));
}else if(exp.charAt(i)=='}' || exp.charAt(i)==']' || exp.charAt(i)==')'){
char c=st.pop();

// System.out.print(c);
if(c=='x'){
return false;
}
if(exp.charAt(i)==')'){
if(c=='('){
val=true;
continue;
}//if there is any other brackets found set val to false;
val=false;
break;
}else if(exp.charAt(i)==']'){
if(c=='['){
val=true;
continue;
}
val=false;
break;
}else if(exp.charAt(i)=='}'){
if(c=='{'){
val=true;
continue;
}
val=false;
break;
}
else{
val=false;
break;
}

}
}
// ex- ([] here it will return true as the last it was found matched
//but there is still one element left in the stack and there is no
//brackets to match further so we keep condition if and only if
//top will go to null such that everything is matched
if(st.top!=null){
return false;
}
return val;
}
}

class Node{

char data;
Node next;
Node(char data){
this.data=data;
}
}

class Stack{

Node top;

public void push(char data){
Node newNode=new Node(data);
if(top==null){
newNode.next=null;
top=newNode;
return;
}
newNode.next=top;
top=newNode;
}

public char pop(){
if(top==null){
return 'x';
}
char c=top.data;
top=top.next;
// System.out.println(c);
return c;
}
}

0 comments on commit 2ba04a4

Please sign in to comment.