gpt4 book ai didi

c++ - 具有堆栈和队列的字符串回文 (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:31 35 4
gpt4 key购买 nike

这可以很好地编译并且在没有空格的情况下也能正常工作,但是一旦我在其中放入空格就会告诉我它不是回文或超时。任何帮助将不胜感激!

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());
}

关于c++ - 具有堆栈和队列的字符串回文 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15595172/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com