/
Stack Permutation.java
45 lines (42 loc) · 979 Bytes
/
Stack Permutation.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
class Solution {
public static int isStackPermutation(int n, int[] ip, int[] op) {
Stack<Integer> stack=new Stack<>();
ArrayList<Integer> res=new ArrayList<>();
int k=0,x=0;
for(int i=0;i<n;i++)
{
if(ip[i]==op[k])
{
res.add(ip[i]);
k++;
while(!stack.isEmpty())
{
if(stack.peek()==op[k])
{
res.add(stack.pop());
k++;
}
else{
break;
}
}
}
else{
stack.push(ip[i]);
}
}
if(res.size()!=op.length)
{
return 0;
}
for(int i:res)
{
if(i!=op[x])
{
return 0;
}
x++;
}
return 1;
}
}