Advertisement
1988coder

946. Validate Stack Sequences

Dec 29th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. /**
  2.  * Time Complexity: O(N)
  3.  *
  4.  * Space Complexity: O(N)
  5.  *
  6.  * N = length of the pushed or popped array.
  7.  */
  8. class Solution {
  9.     public boolean validateStackSequences(int[] pushed, int[] popped) throws IllegalArgumentException {
  10.         if (pushed == null || popped == null) {
  11.             throw new IllegalArgumentException("Input array is null");
  12.         }
  13.         if (pushed.length != popped.length) {
  14.             return false;
  15.         }
  16.  
  17.         Stack<Integer> stack = new Stack();
  18.         int i = 0;
  19.         for (int p : pushed) {
  20.             stack.push(p);
  21.             while (!stack.isEmpty() && stack.peek() == popped[i]) {
  22.                 stack.pop();
  23.                 i++;
  24.             }
  25.         }
  26.  
  27.         return stack.isEmpty();
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement