-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path946. Validate Stack Sequences.java
35 lines (35 loc) · 1.22 KB
/
946. Validate Stack Sequences.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
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
/*
* there is no spcl. algo for that, just traverse and use 2-pointer approch
* and carefully remove the stack.peek() == popped[j] ? stack.pop() : break ;
* after pushing all elems into stack, now traverse from jth to popped.length
* similar check for that also!
*/
int n = pushed.length, j = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
int elem = pushed[i];
stack.add(elem);
j = removeElemfromStack(popped, j, stack);
}
while(j < popped.length) {
int topelem = stack.peek();
int popelem = popped[j];
if (topelem == popelem) { stack.pop(); j++; }
else { return false; }
}
return true;
}
private static int removeElemfromStack(int[] popped, int j, Stack<Integer> stack) {
while(stack.isEmpty()==false) {
if (stack.peek() == popped[j]) {
stack.pop();
j++;
} else {
break;
}
}
return j;
}
}