根據入棧判斷出棧是否合法

來源:互聯網
上載者:User

Description
棧是只能在某一端插入和刪除的特殊線性表。它按照後進先出的原則儲存資料,先進入的資料被壓入棧底,最後的資料在棧頂,需要讀資料的時候從棧頂開始彈出資料(最後一個進棧的資料被第一個讀出來)
給出兩個字串s1和s2,請判斷s1能否通過棧的類比(即進棧和出棧)得到s2?
Input
輸入有多組測試資料,每組輸入佔兩行,s1和s2各佔一行。為了簡化問題,s1和s2保證僅由小寫字母組成,不會出現其它字元;s1和s2等長,且長度不大於100;s2是s1的一種排列,不會在s2中出現s1裡沒有的字元
Output
對於每組輸入,輸出僅佔一行,如果s1能通過棧的類比得到s2,則輸出“YES”;否則輸出“NO”
Sample Input
abcde
baedc
bjfuacm
fujcbma
Sample Output
YES
NO
分析:關於棧有一個很有用的性質,對於出棧序列的每一個元素,該元素後比該元素先入棧的一定按照降序排列。若入棧的是一串數字例如12345,則21435是一個合法的出棧順序,每一個元素i後比i小的都是降序排列(因為入棧的數字代表了進棧先後),24153不是合法的,因為對於4,比它小的1和3的順序不對。

 1 #include <iostream>  2 #include <string> 3 using namespace std; 4 int main() 5 { 6     string s1, s2; 7     while (cin >> s1 >> s2) 8     { 9         int n = s1.size();10         int a1[n], a2[n];            //把字母轉換成數文書處理11         for (int i = 0; i < n; ++i)12         {13             a1[i] = i;14             a2[i] = s1.find(s2[i]);15         }16         int min; bool existless, islegal;17         for (int i = 0; i < n; ++i)18         {19             min = a2[i];20             existless = 0;21             int j;22             for (j = i + 1; j < n; ++j)23                 if (a2[j] < a2[i])       //是否存在比a[i]小的值24                 {25                     min = a2[j];26                     existless = 1;27                     break;28                 }29             islegal = 1;30             if (existless)31             {32                 for (int k = j + 1; k < n; ++k)33                     if (a2[k] < a2[i])34                     {35                         if (a2[k] < min)36                             min = a2[k];    //更新min37                         else38                         {39                             islegal = 0;40                             break;41                         }42                     }43             }44             if (!islegal)45             {    printf("NO\n");    break;    }46         }47         if (islegal)48         printf("YES\n");49     }50     system("pause");51     return 0;52 }

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.