File tree Expand file tree Collapse file tree 2 files changed +111
-0
lines changed
Expand file tree Collapse file tree 2 files changed +111
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments