forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_946.java
58 lines (55 loc) · 1.81 KB
/
_946.java
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
package com.fishercoder.solutions;
import java.util.Stack;
public class _946 {
public static class Solution1 {
public boolean validateStackSequences(int[] pushed, int[] popped) {
if (pushed == null || popped == null || pushed.length == 0 || popped.length == 0) {
return true;
}
Stack<Integer> stack = new Stack<>();
stack.push(pushed[0]);
int i = 1;
int j = 0;
while (!stack.isEmpty() || j < popped.length) {
if (j < popped.length && !stack.isEmpty() && stack.peek() == popped[j]) {
stack.pop();
j++;
} else {
if (i < pushed.length) {
stack.push(pushed[i++]);
} else {
return stack.isEmpty();
}
}
}
return stack.isEmpty();
}
}
public static class Solution2 {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int i = 0;
int j = 0;
int len = pushed.length;
while (i < len) {
if (pushed[i] == popped[j]) {
i++;
j++;
} else if (!stack.isEmpty() && stack.peek() == popped[j]) {
stack.pop();
j++;
} else {
stack.push(pushed[i++]);
}
}
while (j < len) {
if (!stack.isEmpty() && stack.peek() != popped[j++]) {
return false;
} else {
stack.pop();
}
}
return true;
}
}
}