實驗內容
[問題描述]
試寫一個算法,判斷依次讀入的一個以@爲結束符的字母序列,是否爲形如‘序列1&序列2’模式的字符序列。其中序列1和序列2中都不含字符‘&’,且序列2是序列1的逆序列。例如,‘a+b&b+a’是屬該模式的字符序列,而‘1+3&3-1’則不是。
[基本要求]
對於鍵盤輸入的任意一個字符串,將其進行逆置,判斷原串和逆置的串是否完全一致,完全一致則爲迴文,因此分別利用隊列的先進先出(FIFO)和棧的後進先出(FILO)實現,算法只能使用一個棧和一個隊列以及若干簡單類型變量,算法時間複雜度應爲O(n)。
【代碼】
- #include<iostream>
- #include<stack>
- #include<queue>
- using namespace std;
- bool palindrome();
- int main()
- {
- cout<<"請輸入字符串(以@結束,中間部分以&分開)"<<endl;
- if(palindrome()==true)
- {
- cout<<"是迴文。";
- }
- else
- {
- cout<<"不是迴文。";
- }
- system("pause");
- }
- bool palindrome()
- {
- stack<char> s;
- queue<char> q;
- char str;
- while((str=getchar())!='@')
- {
- q.push(str);
- s.push(str);
- }
- if(s.size()%2==0)
- {
- return false;
- }
- else
- {
- while(!s.empty() && !q.empty())
- if(s.top()!=q.front())
- return false;
- else
- return true;
- }
- }
實驗內容
[問題描述]
試寫一個算法,判斷依次讀入的一個以@爲結束符的字母序列,是否爲形如‘序列1&序列2’模式的字符序列。其中序列1和序列2中都不含字符‘&’,且序列2是序列1的逆序列。例如,‘a+b&b+a’是屬該模式的字符序列,而‘1+3&3-1’則不是。
[基本要求]
對於鍵盤輸入的任意一個字符串,將其進行逆置,判斷原串和逆置的串是否完全一致,完全一致則爲迴文,因此分別利用隊列的先進先出(FIFO)和棧的後進先出(FILO)實現,算法只能使用一個棧和一個隊列以及若干簡單類型變量,算法時間複雜度應爲O(n)。
【代碼】
- #include<iostream>
- #include<stack>
- #include<queue>
- using namespace std;
- bool palindrome();
- int main()
- {
- cout<<"請輸入字符串(以@結束,中間部分以&分開)"<<endl;
- if(palindrome()==true)
- {
- cout<<"是迴文。";
- }
- else
- {
- cout<<"不是迴文。";
- }
- system("pause");
- }
- bool palindrome()
- {
- stack<char> s;
- queue<char> q;
- char str;
- while((str=getchar())!='@')
- {
- q.push(str);
- s.push(str);
- }
- if(s.size()%2==0)
- {
- return false;
- }
- else
- {
- while(!s.empty() && !q.empty())
- if(s.top()!=q.front())
- return false;
- else
- return true;
- }
- }
【運行結果】
注:以上內容僅供參考,如有問題歡迎指正