带有堆栈和队列的字符串回文(c++)
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");
}
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- Usaco第1.6节主要回文
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 将 S1 转换为回文,并将 S2 作为其子字符串
- 数回文词
- 最长的回文子串(C++帮助)
- 有人可以详细解释这个回文代码是如何工作的吗?
- 回文递归版本
- 如何检查C ++ STL列表是否为回文?
- 回文数在 1 到 10000 之间
- C++ - 检查结构数据类型中的单词是否为回文
- 是回文作业练习
- 回文递归不停止
- 整数数组中最长的回文
- 回文测试
- 最大的回文产品(Project Euler)——C++
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 递归回文问题的时间复杂度,C++
- 程序以查找给定字符串中回文的子字符串的数量
- 递归回文检查,不使用向量、大小或其他参数