|
| 1 | +/** |
| 2 | +* Given two sequences pushed and popped with distinct values, return true if and |
| 3 | +* only if this could have been the result of a sequence of push and pop operations on an initially empty stack. |
| 4 | +* |
| 5 | +* Example 1: |
| 6 | +* Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] |
| 7 | +* Output: true |
| 8 | +* Explanation: We might do the following sequence: |
| 9 | +* push(1), push(2), push(3), push(4), pop() -> 4, |
| 10 | +* push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 |
| 11 | +* |
| 12 | +* Example 2: |
| 13 | +* Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] |
| 14 | +* Output: false |
| 15 | +* Explanation: 1 cannot be popped before 2. |
| 16 | +* |
| 17 | +* Note: |
| 18 | +* 0 <= pushed.length == popped.length <= 1000 |
| 19 | +* 0 <= pushed[i], popped[i] < 1000 |
| 20 | +* pushed is a permutation of popped. |
| 21 | +* pushed and popped have distinct values. |
| 22 | +*/ |
| 23 | +public class ValidateStackSequences946 { |
| 24 | +public boolean validateStackSequences(int[] pushed, int[] popped) { |
| 25 | +int i = 0; |
| 26 | +int j = 0; |
| 27 | +int len = pushed.length; |
| 28 | +Stack<Integer> st = new Stack<>(); |
| 29 | +while (i < len && j < len) { |
| 30 | +while (!st.isEmpty() && j < len && popped[j] == st.peek()) { |
| 31 | +j++; |
| 32 | +st.pop(); |
| 33 | +} |
| 34 | +if (j >= len) break; |
| 35 | +while (i < len && pushed[i] != popped[j]) { |
| 36 | +st.push(pushed[i]); |
| 37 | +i++; |
| 38 | +} |
| 39 | +if (i < len && pushed[i] == popped[j]) { |
| 40 | +st.push(pushed[i]); |
| 41 | +i++; |
| 42 | +} |
| 43 | +} |
| 44 | +while (!st.isEmpty() && j < len && popped[j] == st.peek()) { |
| 45 | +j++; |
| 46 | +st.pop(); |
| 47 | +} |
| 48 | +return i == len && j == len && st.isEmpty(); |
| 49 | +} |
| 50 | +} |
0 commit comments