-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathValid Stack Permutation
More file actions
37 lines (31 loc) · 883 Bytes
/
Valid Stack Permutation
File metadata and controls
37 lines (31 loc) · 883 Bytes
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
code in java
***************************************************
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public static boolean validStackPermutation(ArrayList<Integer> first, ArrayList<Integer> other) {
// Make a stack to store the elements.
Stack<Integer> st = new Stack<Integer>();
// Pointer to point the elements in the 'OTHER' array.
int p = 0;
// Iterate over the first array.
for (int i = 0; i < first.size(); i++) {
// Push each element of first array into the 'OTHER' array.
st.push(first.get(i));
while (!st.empty() && (other.get(p).intValue() == st.peek().intValue())) {
// Increment the pointer.
p++;
// Pop the top element.
st.pop();
}
}
// If the stack is empty, return "YES".
if (st.empty()) {
return true;
}
// Otherwise, return "NO".
else {
return false;
}
}
}