Skip to content

Commit d29fcc4

Browse files
author
Vinay Patel
committed
Stack Question
1 parent ed2bdf7 commit d29fcc4

File tree

2 files changed

+111
-0
lines changed

2 files changed

+111
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package NeetCode_150_DSA.Stack;
2+
3+
import java.util.Stack;
4+
5+
class MinStack {
6+
private Stack<Integer> s; // stack
7+
private Stack<Integer> miniS; // minStack
8+
9+
public MinStack() {
10+
s = new Stack<>();
11+
miniS = new Stack<>();
12+
}
13+
14+
public void push(int value) {
15+
s.push(value);
16+
17+
if (miniS.isEmpty() || value <= miniS.peek()) {
18+
miniS.push(value);
19+
}
20+
}
21+
22+
public void pop() {
23+
if (!s.isEmpty()) {
24+
int popped = s.pop();
25+
26+
if (!miniS.isEmpty() && popped == miniS.peek()) {
27+
miniS.pop();
28+
}
29+
}
30+
}
31+
32+
public int top() {
33+
if (!s.isEmpty()) {
34+
return s.peek();
35+
}
36+
return -1;
37+
}
38+
39+
public int getMin() {
40+
if (!miniS.isEmpty()) {
41+
return miniS.peek();
42+
}
43+
return -1;
44+
}
45+
46+
}
47+
48+
public class Min_Stack_2 {
49+
public static void main(String[] args) {
50+
MinStack obj = new MinStack();
51+
int value;
52+
obj.push(value);
53+
obj.pop();
54+
int param_3 = obj.top();
55+
int param_4 = obj.getMin();
56+
}
57+
58+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package NeetCode_150_DSA.Stack;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.Stack;
6+
7+
public class Valid_Parentheses_1 {
8+
9+
public static void main(String[] args) {
10+
11+
}
12+
public boolean isValid(String s) {
13+
// Brute Force
14+
/*
15+
Stack<Character> stack = new Stack<>();
16+
17+
for(char c:s.toCharArray()){
18+
if(c=='(' || c=='{' || c=='['){
19+
stack.push(c);
20+
}else if(c==')' && !stack.isEmpty() && stack.peek()=='('){
21+
stack.pop();
22+
}else if(c=='}' && !stack.isEmpty() && stack.peek()=='{'){
23+
stack.pop();
24+
}else if(c==']' && !stack.isEmpty() && stack.peek()=='['){
25+
stack.pop();
26+
}else{
27+
return false;
28+
}
29+
}
30+
return stack.isEmpty();
31+
*/
32+
33+
// We can eliminate the need for the separate if-else statements by using a map to store the mappings of opening and closing parentheses
34+
Stack<Character> stack = new Stack<>();
35+
Map<Character, Character> mappings = new HashMap<>();
36+
37+
mappings.put(')','(');
38+
mappings.put('}','{');
39+
mappings.put(']','[');
40+
41+
for(char c:s.toCharArray()){
42+
if(mappings.containsKey(c)){
43+
char topEle = stack.isEmpty() ? '#' : stack.pop();
44+
if(topEle != mappings.get(c)){
45+
return false;
46+
}
47+
}else{
48+
stack.push(c);
49+
}
50+
}
51+
return stack.isEmpty();
52+
}
53+
}

0 commit comments

Comments
 (0)