Skip to content

Commit 4c03f0b

Browse files
authored
Merge pull request #45 from Jer3myYu/java-solutions-stacks
Java Chapter 7: Stacks
2 parents e7e6a97 + 8022168 commit 4c03f0b

6 files changed

+198
-0
lines changed

java/Stacks/EvaluateExpression.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.Stack;
2+
3+
public class EvaluateExpression {
4+
public int evaluateExpression(String s) {
5+
Stack<Integer> stack = new Stack<>();
6+
int currNum = 0;
7+
int sign = 1;
8+
int res = 0;
9+
for (char c : s.toCharArray()) {
10+
if (Character.isDigit(c)) {
11+
currNum = currNum * 10 + c - '0';
12+
}
13+
// If the current character is an operator, add 'currNum' to
14+
// the result after multiplying it by its sign.
15+
else if (c == '+' || c == '-') {
16+
res += currNum * sign;
17+
// Update the sign and reset 'curr_num'.
18+
sign = c == '-' ? -1 : 1;
19+
currNum = 0;
20+
}
21+
// If the current character is an opening parenthesis, a new
22+
// nested expression is starting.
23+
else if (c == '(') {
24+
// Save the current 'res' and 'sign' values by pushing them
25+
// onto the stack, then reset their values to start
26+
// calculating the new nested expression.
27+
stack.push(res);
28+
stack.push(sign);
29+
res = 0;
30+
sign = 1;
31+
}
32+
// If the current character is a closing parenthesis, a nested
33+
// expression has ended.
34+
else if (c == ')') {
35+
// Finalize the result of the current nested expression.
36+
res += sign * currNum;
37+
// Apply the sign of the current nested expression's result
38+
// before adding this result to the result of the outer
39+
// expression.
40+
res *= stack.pop();
41+
res += stack.pop();
42+
currNum = 0;
43+
}
44+
}
45+
// Finalize the result of the overall expression.
46+
return res + currNum * sign;
47+
}
48+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.Stack;
2+
3+
public class ImplementAQueueUsingAStack {
4+
Stack<Integer> enqueueStack;
5+
Stack<Integer> dequeueStack;
6+
7+
public ImplementAQueueUsingAStack() {
8+
this.enqueueStack = new Stack<>();
9+
this.dequeueStack = new Stack<>();
10+
}
11+
12+
public void enqueue(int x) {
13+
this.enqueueStack.push(x);
14+
}
15+
16+
private void transferEnqueueToDequeue() {
17+
// If the dequeue stack is empty, push all elements from the enqueue stack
18+
// onto the dequeue stack. This ensures the top of the dequeue stack
19+
// contains the most recent value.
20+
if (this.dequeueStack.isEmpty()) {
21+
while (!this.enqueueStack.isEmpty()) {
22+
this.dequeueStack.push(enqueueStack.pop());
23+
}
24+
}
25+
}
26+
27+
public int dequeue() {
28+
transferEnqueueToDequeue();;
29+
// Pop and return the value at the top of the dequeue stack.
30+
return this.dequeueStack.isEmpty() ? null : this.dequeueStack.pop();
31+
}
32+
33+
public int peek() {
34+
transferEnqueueToDequeue();;
35+
return this.dequeueStack.isEmpty() ? null : this.dequeueStack.peek();
36+
}
37+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.Stack;
2+
3+
public class MaximumsOfSlidingWindow {
4+
public int[] maximumsOfSlidingWindow(int[] nums, int k) {
5+
int[] res = new int[nums.length - k + 1];
6+
Stack<int[]> dq = new Stack<>();
7+
int left, right;
8+
left = right = 0;
9+
while (right < nums.length) {
10+
// 1) Ensure the values of the deque maintain a monotonic decreasing order
11+
// by removing candidates <= the current candidate.
12+
while (!dq.isEmpty() && dq.peek()[0] <= nums[right]) {
13+
dq.pop();
14+
}
15+
// 2) Add the current candidate.
16+
dq.push(new int[]{nums[right], right});
17+
// If the window is of length 'k', record the maximum of the window.
18+
if (right - left + 1 == k) {
19+
// 3) Remove values whose indexes occur outside the window.
20+
if (!dq.isEmpty() && dq.firstElement()[1] < left) {
21+
dq.remove(0);
22+
}
23+
// The maximum value of this window is the leftmost value in the
24+
// deque.
25+
res[left] = dq.firstElement()[0];
26+
// Slide the window by advancing both 'left' and 'right'. The right
27+
// pointer always gets advanced so we just need to advance 'left'.
28+
left++;
29+
}
30+
right++;
31+
}
32+
return res;
33+
}
34+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.util.Stack;
2+
3+
public class NextLargestNumberToTheRight {
4+
public int[] nextLargestNumberToTheRight(int[] nums) {
5+
int[] res = new int[nums.length];
6+
Stack<Integer> stack = new Stack<>();
7+
// Find the next largest number of each element, starting with the
8+
// rightmost element.
9+
for (int i = nums.length - 1; i >= 0; i--) {
10+
// Pop values from the top of the stack until the current
11+
// value's next largest number is at the top.
12+
while (!stack.isEmpty() && stack.peek() <= nums[i]) {
13+
stack.pop();
14+
}
15+
// Record the current value's next largest number, which is at
16+
// the top of the stack. If the stack is empty, record -1.
17+
res[i] = stack.isEmpty() ? -1 : stack.peek();
18+
stack.push(nums[i]);
19+
}
20+
return res;
21+
}
22+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import java.util.Stack;
2+
3+
public class RepeatedRemovalOfAdjacentDuplicates {
4+
public String repeatedRemovalOfAdjacentDuplicates(String s) {
5+
Stack<Character> stack = new Stack<>();
6+
StringBuilder res = new StringBuilder();
7+
for (char c : s.toCharArray()) {
8+
// If the current character is the same as the top character on the stack,
9+
// a pair of adjacent duplicates has been formed. So, pop the top character
10+
// from the stack.
11+
if (!stack.isEmpty() && c == stack.peek()) {
12+
stack.pop();
13+
}
14+
// Otherwise, push the current character onto the stack.
15+
else {
16+
stack.push(c);
17+
}
18+
}
19+
// Return the remaining characters as a string.
20+
for (char c : stack) {
21+
res.append(c);
22+
}
23+
return res.toString();
24+
}
25+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
import java.util.Stack;
4+
5+
public class ValidParenthesisExpression {
6+
public boolean validParenthesisExpression(String s) {
7+
Map<Character, Character> parenthesesMap = new HashMap<>();
8+
Stack<Character> stack = new Stack<>();
9+
parenthesesMap.put('(', ')');
10+
parenthesesMap.put('{', '}');
11+
parenthesesMap.put('[', ']');
12+
for (char c : s.toCharArray()) {
13+
// If the current character is an opening parenthesis, push it
14+
// onto the stack.
15+
if (parenthesesMap.containsKey(c)) {
16+
stack.push(c);
17+
}
18+
// If the current character is a closing parenthesis, check if
19+
// it closes the opening parenthesis at the top of the stack.
20+
else {
21+
if (!stack.isEmpty() && parenthesesMap.get(stack.peek()) == c) {
22+
stack.pop();
23+
} else {
24+
return false;
25+
}
26+
}
27+
}
28+
// If the stack is empty, all opening parentheses were successfully
29+
// closed.
30+
return stack.isEmpty();
31+
}
32+
}

0 commit comments

Comments
 (0)