輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能爲該棧的彈出順序。

//方案一:java

import java.util.*;code

public class Solution {io

public boolean IsPopOrder(int [] pushA,int [] popA) {

     Stack<Integer> stack =new Stack<Integer>();
    int j=0;
    
    for(int i=0;i<pushA.length;i++)
    {
        if(pushA[i]==popA[j])
        {
            j++;
            
            while(!stack.isEmpty()&&j<pushA.length&&stack.peek()==popA[j]){
                    stack.pop();
                    j++;
            }
        }
        else
            stack.push(pushA[i]);

    }
    
    return stack.isEmpty();
}

}class

//方案二:import

public class Solution {im

public boolean IsPopOrder(int [] pushA,int [] popA) {

     Stack<Integer> stack =new Stack<Integer>();
     
     int i=0,j=0;
     boolean res=true;
    
    while(j<pushA.length){
        
        if(i<pushA.length&&pushA[i]==popA[j])
        {i++;
         j++;
        }
        
        else if(!stack.isEmpty()&&stack.peek()==popA[j])
        {stack.pop();
         j++;
        }
        
        else  if(i<pushA.length) 
        {stack.push(pushA[i]);
         i++;
        }
        else {res=false;break;}
    }
    
    return res;
}

}while

相關文章
相關標籤/搜索