【劍指offer】十四,棧的壓入、彈出序列

來源:互聯網
上載者:User

標籤:

題目描述輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。 代碼如下:
 1 import java.util.Stack; 2   3 public class Solution { 4      public boolean IsPopOrder(int [] pushA,int [] popA) { 5             Stack<Integer> s  = new Stack<Integer>() ; 6             int j = 0 ;
//邊界條件判定
7 if(pushA.length!=popA.length||pushA.length ==0||popA.length==0){ 8 return false ; 9 }
        //如果兩個序列的一個字元相同,則將該字元入棧再出棧,若不同,則將其入棧
10 for(int i = 0 ;i < pushA.length ;i++){11 if(pushA[i] == popA[j]){12 s.push(pushA[i]) ;13 s.pop() ;14 j++ ;15 }16 else17 s.push(pushA[i]) ;18 }19 if(s.empty()){20 return true ;21 }22 while(!s.empty()){23 if(s.peek()!=popA[j]){24 return false ;25 }26 else27 {28 s.pop() ;29 j++ ;30 }31 }32 return true ;33 }34 }

 

【劍指offer】十四,棧的壓入、彈出序列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.