Skip to content

Commit

Permalink
Stacks Assignment Solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
shivajipotnuru committed Jun 19, 2020
1 parent 2956982 commit e143ea5
Show file tree
Hide file tree
Showing 3 changed files with 127 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Stacks Assignment/Check redundant brackets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import java.util.Stack;

public class solution {

public static boolean checkRedundantBrackets(String s) {
// Write your code here
Stack<Character> st = new Stack<>();
char[] str = s.toCharArray();

for (char ch : str) {


if (ch == ')') {
char top = st.peek();
st.pop();

boolean flag = true;

while (top != '(') {

if (top == '+' || top == '-'|| top == '*' || top == '/') {
flag = false;
}
top = st.peek();
st.pop();
}


if (flag == true) {
return true;
}
} else {
st.push(ch);
}
}
return false;

}
}
58 changes: 58 additions & 0 deletions Stacks Assignment/Minimum bracket Reversal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import java.util.*;

public class Solution {


// Function returns -1 if brackets can't be balanced
public static int countBracketReversals(String expr){

// Write your code here
int len = expr.length();

// length of expression must be even to make
// it balanced by using reversals.
if (len%2 != 0)
return -1;

// After this loop, stack contains unbalanced
// part of expression, i.e., expression of the
// form "}}..}{{..{"
Stack<Character> s=new Stack<>();

for (int i=0; i<len; i++)
{
char c = expr.charAt(i);
if (c =='}' && !s.empty())
{
if (s.peek()=='{')
s.pop();
else
s.push(c);
}
else
s.push(c);
}

// Length of the reduced expression
// red_len = (m+n)
int red_len = s.size();

// count opening brackets at the end of
// stack
int n = 0;
while (!s.empty() && s.peek() == '{')
{
s.pop();
n++;
}

// return ceil(m/2) + ceil(n/2) which is
// actually equal to (m+n)/2 + n%2 when
// m+n is even.
return (red_len/2 + n%2);

}



}
30 changes: 30 additions & 0 deletions Stacks Assignment/Stock Span.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import java.util.Arrays;
import java.util.Stack;

public class Solution {

public static int[] stockSpan(int[] price) {
// Write your code here
Stack<Integer> st =new Stack<Integer>();
// st.push(1);
int span[] =new int[price.length];
for(int i=0;i<price.length;i++){
// st.push[i];
while(!st.isEmpty() && price[st.peek()]< price [i])
{
st.pop();
}
if(st.isEmpty()){
span[i]=i+1;
}
else
span[i]=i-st.peek();
st.push(i);


}
return span;

}

}

0 comments on commit e143ea5

Please sign in to comment.