題目:輸入兩個整數序列。其中一個序列表示棧的push順序,
判斷另一個序列有沒有可能是對應的pop順序。
為了簡單起見,我們假設push序列的任意兩個整數都是不相等的。
比如:
輸入的push序列是1,2,3,4,5 ,那麼4,5,3,2,1就有可能是一個pop序列。
因為可以有如下的push和pop序列:
push 1, push 2, push 3, push 4, pop, push 5, pop, pop, pop, pop
這樣的的得到的pop序列就是4,5,3,2,1.
但是序列4,3,5,1,2就不可能是push序列1,2,3,4,5的pop序列。因為我可以類比如下:
push 1, push 2, push 3, push 4, pop(4), pop(3), push 5, pop(5), pop(2)--->得不到1
分析:
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
在例子中我們可以看到判斷的過程,我們可以用程式類比這個過程。
請看代碼實現:
#include<iostream> using namespace std; template<int MAXSIZE=1024> class Stack{ private: int data[MAXSIZE]; int pos; public: Stack():pos(0){} bool empty() { return pos == 0; } bool full() { return pos == MAXSIZE; } bool get(int& _value) { if(empty()) return false; _value = data[pos-1]; return true; } bool pop(int& _value) { if(empty()) return false; _value = data[--pos]; return true; } bool push(int& _value) { if(full()) return false; data[pos] = _value; pos ++; return true; } }; bool trueSequence(int* push_str,int len, int* pop_str) { if(len == 0) return true; int i = 0; int j = 0; Stack<1024> s; while(i < len) { int v; if( j < len && pop_str[i] == push_str[j]) { i ++; j ++; continue; } else { if(s.get(v)) { if(v!= pop_str[i]) { if(j >= len) break; s.push(push_str[j]); j ++; } else { s.pop(v); i ++; } } else { if(j >= len) break; s.push(push_str[j]); j ++; } } } if(i == j) return true; else return false; } int main() { int push1[5] = {1,2,3,4,5}; int pop1[5] = {4,5,3,2,1}; if(trueSequence(push1, 5, pop1)) cout << "push Sequence:1 2,3,4,5; 4,5,3,2,1 is a pop sequence" << endl; else cout << "push Sequence:1 2,3,4,5; 4,5,3,2,1 is not a pop sequence" << endl; int pop2[5] = {4,3,5,1,2}; if(trueSequence(push1, 5, pop2)) cout << "push Sequence:1 2,3,4,5; 4,3,5,1,2 is a pop sequence" << endl; else cout << "push Sequence:1 2,3,4,5; 4,3,5,1,2 is not a pop sequence" << endl; return 0; }
輸出結果為:
push Sequence:1 2,3,4,5; 4,5,3,2,1 is a pop sequence
push Sequence:1 2,3,4,5; 4,3,5,1,2 is not a pop sequence
作者:csdn部落格 hhh3h