gpt4 book ai didi

c++ - 谁能检查这个 Palindrome c++ 代码是否正确?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:40:45 24 4
gpt4 key购买 nike

这是我用 C++ 编写的用于检查回文单词的程序。它不以通常的方式工作(反转单词并检查是否相同),而是直接从头到尾检查每个单词;

madam、ada、hannah、racecar 是我试过的词,它们似乎是正确的。

    #include <iostream>

std::string is_palindrome(std::string text)
{
int length=text.size(); //No. of characters
int index=text.size()-1; //No. of indexes
int i;
int x=0; //To store no of same character from both ends
for(i=0;i<=index;i++)
{
if(text[i]==text[index-i])
{x++;}
}
if(x==length) //If all characters are same form opp ends
{
return "true";
}
else
{
return "false";
}
}

int main() {

std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("happy") << "\n";

}

结果是正确的,我只是找不到这样的代码,所以只是想检查一下。

最佳答案

你的函数太复杂了。参数应该是常量引用类型,函数应该返回 bool 值。

下面是一个演示程序,展示了函数如何使用循环。

#include <iostream>
#include <iomanip>
#include <string>

bool is_palindrome( const std::string &s )
{
std::string::size_type i = 0, n = s.length();

while ( i < n / 2 && s[i] == s[n - i - 1] ) ++i;

return i == n / 2;
}

int main()
{
std::cout << std::boolalpha << is_palindrome( "madam" ) << "\n";
std::cout << std::boolalpha << is_palindrome( "happy" ) << "\n";

return 0;
}

它的输出是

true
false

您可以编写更短的函数,如下面的演示程序所示。但是该函数的效率低于使用循环的函数,因为它需要为临时字符串分配内存 std::string( std::rbegin( s ), std::rend( s ) )

#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>

bool is_palindrome( const std::string &s )
{
return s == std::string( std::rbegin( s ), std::rend( s ) );
}

int main()
{
std::cout << std::boolalpha << is_palindrome( "madam" ) << "\n";
std::cout << std::boolalpha << is_palindrome( "happy" ) << "\n";

return 0;
}

程序输出与上图相同

true
false

关于c++ - 谁能检查这个 Palindrome c++ 代码是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645433/

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