[英]String Palindrome with stack and queue (C++)
這可以很好地編譯並且在沒有空格的情況下也可以很好地工作,但是一旦我在其中放入空格,要么告訴我它不是回文或者超時。 任何幫助將不勝感激!
int main( )
{
queue<char> q;
stack<char> s;
string the_string;
int mismatches = 0;
cout << "Enter a line and I will see if it's a palindrome:" << endl;
cin >> the_string;
int i = 0;
while (cin.peek() != '\n')
{
cin >> the_string[i];
if (isalpha(the_string[i]))
{
q.push(toupper(the_string[i]));
s.push(toupper(the_string[i]));
}
i++;
}
while ((!q.empty()) && (!s.empty()))
{
if (q.front() != s.top())
++mismatches;
q.pop();
s.pop();
}
if (mismatches == 0)
cout << "This is a palindrome" << endl;
else
cout << "This is not a palindrome" << endl;
system("pause");
return EXIT_SUCCESS;
}
為什么這么復雜?
您可以簡單地執行以下操作:
#include <string>
#include <algorithm>
bool is_palindrome(std::string const& s)
{
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
首先是線
cin >> the_string;
沒有得到整條線。 改用這個
getline(cin, the_string);
其次,在調試算法時會打印出很多信息。 例如,如果您添加行
cout << "You entered: '" << the_string << "'" << endl;
您可以輕松查看實際測試的字符串。
我有這個解決方案可以正常工作。
int main( )
{
queue<char> q;
stack<char> s;
string the_string;
int mismatches = 0;
cout << "Enter a line and I will see if it's a palindrome:" << endl;
int i = 0;
while (cin.peek() != '\n')
{
cin >> the_string[i];
if (isalpha(the_string[i]))
{
q.push(toupper(the_string[i]));
s.push(toupper(the_string[i]));
}
i++;
}
while ((!q.empty()) && (!s.empty()))
{
if (q.front() != s.top())
++mismatches;
q.pop();
s.pop();
}
if (mismatches == 0)
cout << "This is a palindrome" << endl;
else
cout << "This is not a palindrome" << endl;
system("pause");
return EXIT_SUCCESS;
}
void main()
{
queue<char> q;
stack<char> s;
char letter;
int mismatches = 0;
cout << "Enter a word and I will see if it's a palindrome:" << endl;
cin >> letter;
q.push(letter);
s.push(letter);
int i = 0;
while (cin.peek() != '\n')
{
cin >> letter;
if (isalpha(letter))
{
q.push(letter);
s.push(letter);
}
i++;
}
while ((!q.empty()) && (!s.empty()))
{
if (q.front() != s.top())
++mismatches;
q.pop();
s.pop();
}
if (mismatches == 0)
{
cout << "This is a palindrome" << endl;
}
else
{
cout << "This is not a palindrome" << endl;
}
cout << endl;
cout << "Homework done!" << endl;
cout << "You are Welcome!" << endl;
system("pause");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.