这个编译很好并且没有空格,但是一旦我在其中放置空格要么告诉我它不是回文或超时。任何帮助将不胜感激!
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;
}
答案 0 :(得分:1)
为什么这么复杂?
你可以这样做:
#include <string>
#include <algorithm>
bool is_palindrome(std::string const& s)
{
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
答案 1 :(得分:1)
首先是
行cin >> the_string;
没有得到整行。请改用
getline(cin, the_string);
其次,在调试算法时会打印出大量信息。例如,如果添加行
cout << "You entered: '" << the_string << "'" << endl;
您可以轻松查看实际测试的字符串。
答案 2 :(得分:1)
我让这个解决方案工作正常。
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;
}
答案 3 :(得分:-1)
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");
}