Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Approach
Java
import java.util.Stack;public class ValidateStackSequence {public static void main(String[] args) {int pushed[] = { 1, 2, 3, 4, 5 }, popped[] = { 4, 5, 3, 2, 1 };System.out.println(validateStackSequences(pushed, popped));}public static boolean validateStackSequences(int[] pushed, int[] popped) {Stack<Integer> st = new Stack<Integer>();int j = 0;// iterate through the whole arrayfor (int i = 0; i < pushed.length; i++) {// insert the current element into stackst.push(pushed[i]);// iterate till the size of stack is greater than 0 and// current element is the stack top elementwhile (st.size() > 0) {if (popped[j] == st.peek()) {st.pop();j++;} elsebreak;}}// iterate through the remaining elements of the popped// arrayfor (int i = j; i < popped.length; i++) {// if at any point top element is not// equal to the current element then// return falseif (st.peek() != popped[i]) {return false;}}// at the end return truereturn true;}}
C++
#include <bits/stdc++.h>using namespace std;bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {stack<int> st;int j=0;// iterate through the whole arrayfor (int i = 0; i < pushed.size(); i++) {// insert the current element into stackst.push(pushed[i]);// iterate till the size of stack is greater than 0 and// current element is the stack top elementwhile (st.size() > 0) {if (popped[j] == st.top()) {st.pop();j++;} elsebreak;}}// iterate through the remaining elements of the popped// arrayfor (int i = j; i < popped.size(); i++) {// if at any point top element is not// equal to the current element then// return falseif (st.top() != popped[i]) {return false;}}// at the end return truereturn true;}int main(){vector<int> pushed = { 1, 2, 3, 4, 5 },popped = { 4, 5, 3, 2, 1 };cout << validateStackSequences(pushed,popped);return 0;}
No comments:
Post a Comment