C++ 回文函数

问题描述 投票:0回答:5

代码

#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(string str)
{
    for(int i = 0; i <= str.length()-1; i++)
    {
        if(str[i] != str[str.length()-1-i])
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

int main()
{
    string text;

    do
    {
        cout << "Enter some Text: " << endl;
        cin >> text;
        if(isPalindrome(text))
        {
            cout << "The text is a palindrome" << endl;
        }
        else
        {
            cout << "The text is not a palindrome" << endl;
        }

    }while(text != "Q");

    return 0;
}

输入_1

otto

输出

The text is a palindrome

输入_2

 ottop

输出

The text is a palindrome

输入_3

ottopo

输出3

The text is a palindrome

我想检查用户输入的字符串是否是回文?为什么我的第三个输入的输出出错?我想我错过了一些东西。

c++ function palindrome
5个回答
4
投票

您在循环的第一次迭代中返回 true。你只需要迭代一半的字符串。

更正:

    size_t len = str.length();

    for(int i = 0; i < len/2; i++){
        if(str[i] != str[len-1-i]){
            return false;
        }
    }
    return true;

0
投票

else 语句后面不必有

return true
。将其放在 for 循环之外,您的代码应该可以工作。

作为一个额外的挑剔,你不必检查直到 strlen(s) - 1,但 strlen(s) / 2 实际上就足够了。我将把这个问题留给你来解决,因为它非常简单,并且与你正在做的事情没有太大不同。


0
投票

正如已经说过的,

return true;
不应该在
else
中,而应该在
for
循环结束之后。这也只需几行即可完成。如果一个字符串与正常情况一样颠倒过来,那么它就是回文串。你所需要的只是

reversedText = reverse(text.begin(), text.end());
if (text == reversedText)
    //indicate that it is a palindrome
else
    //indicate that it is not a palindrome`

请务必包含算法。如果您出于某种原因不想使用库,我可以理解,但我只是想确保您知道这可以很容易地完成。


0
投票

如果输入包含字母、数字、符号和空格怎么办 我们必须忽略符号和空格 什么?


-1
投票

如果不是回文,您应该将标志设置为

1
,然后在以下位置中断:

for (int i = 0; i < len/2; i++) {
    if (str[i] != str[len-1-i]) {
        // here .......
    }
© www.soinside.com 2019 - 2024. All rights reserved.