-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStackUtils.java
More file actions
181 lines (146 loc) · 5.4 KB
/
Copy pathStackUtils.java
File metadata and controls
181 lines (146 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package alg.stackproblems;
import alg.misc.InterestingAlgorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Common stack-based interview patterns.
*/
public class StackUtils {
/**
* Returns true if the string has valid matching parentheses, brackets, and braces.
*/
@InterestingAlgorithm(timeComplexity = "O(n)", spaceComplexity = "O(n)")
public static boolean isValidParentheses (String s) {
if (s == null || s.length() == 0)
return (true);
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
}
else {
if (stack.isEmpty())
return (false);
char top = stack.pop();
if (c == ')' && top != '(')
return (false);
if (c == ']' && top != '[')
return (false);
if (c == '}' && top != '{')
return (false);
}
}
return (stack.isEmpty());
}
/**
* Evaluates a reverse Polish notation expression.
*/
@InterestingAlgorithm(timeComplexity = "O(n)", spaceComplexity = "O(n)")
public static int evalRPN (String [] tokens) {
if (tokens == null || tokens.length == 0)
throw new IllegalArgumentException("Invalid input");
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
String token = tokens [i];
if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
int b = stack.pop();
int a = stack.pop();
if (token.equals("+"))
stack.push(a + b);
else if (token.equals("-"))
stack.push(a - b);
else if (token.equals("*"))
stack.push(a * b);
else
stack.push(a / b);
}
else {
stack.push(Integer.parseInt(token));
}
}
return (stack.pop());
}
/**
* For each day, returns the number of days until a warmer temperature.
* Returns 0 if no warmer day exists.
*/
@InterestingAlgorithm(timeComplexity = "O(n)", spaceComplexity = "O(n)")
public static int [] dailyTemperatures (int [] temperatures) {
if (temperatures == null || temperatures.length == 0)
return (new int [0]);
int n = temperatures.length;
int [] result = new int [n];
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && temperatures [i] > temperatures [stack.peek()]) {
int idx = stack.pop();
result [idx] = i - idx;
}
stack.push(i);
}
return (result);
}
/**
* Returns the area of the largest rectangle that can be formed in the histogram.
*/
@InterestingAlgorithm(timeComplexity = "O(n)", spaceComplexity = "O(n)")
public static int largestRectangleInHistogram (int [] heights) {
if (heights == null || heights.length == 0)
return (0);
Stack<Integer> stack = new Stack<Integer>();
int maxArea = 0;
for (int i = 0; i <= heights.length; i++) {
int curHeight = (i == heights.length) ? 0 : heights [i];
while (!stack.isEmpty() && curHeight < heights [stack.peek()]) {
int height = heights [stack.pop()];
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
int area = height * width;
if (area > maxArea)
maxArea = area;
}
stack.push(i);
}
return (maxArea);
}
/**
* A stack that supports push, pop, top, and getMin all in O(1) time.
*/
public static class MinStack {
private List<Integer> data;
private List<Integer> mins;
public MinStack () {
data = new ArrayList<Integer>();
mins = new ArrayList<Integer>();
}
@InterestingAlgorithm(timeComplexity = "O(1)", spaceComplexity = "O(1)")
public void push (int val) {
data.add(val);
if (mins.isEmpty() || val <= mins.get(mins.size() - 1))
mins.add(val);
else
mins.add(mins.get(mins.size() - 1));
}
@InterestingAlgorithm(timeComplexity = "O(1)", spaceComplexity = "O(1)")
public int pop () {
if (data.isEmpty())
throw new RuntimeException("Empty stack");
int val = data.remove(data.size() - 1);
mins.remove(mins.size() - 1);
return (val);
}
@InterestingAlgorithm(timeComplexity = "O(1)", spaceComplexity = "O(1)")
public int top () {
if (data.isEmpty())
throw new RuntimeException("Empty stack");
return (data.get(data.size() - 1));
}
@InterestingAlgorithm(timeComplexity = "O(1)", spaceComplexity = "O(1)")
public int getMin () {
if (mins.isEmpty())
throw new RuntimeException("Empty stack");
return (mins.get(mins.size() - 1));
}
}
}