验证字符串是否为回文的函数

Function that verify's if the string is a palindrom

本文关键字:函数 回文 字符串 是否 验证      更新时间:2023-10-16

现在我正在编写一个程序,该程序告诉您输入的字符串是否为回文,而我正停留在最后一步。有三个基本函数可以删除句子中的所有空格,将它们降到小写,然后反转它们,然后我的函数验证它们,然后返回布尔值。所以现在在这个功能中,生日快乐!会以yadhtribippah的身份出现。到目前为止,这就是我的功能:

string updated1;
string updated2;
updated1 = makeLower(verify);
updated2 = removeNonLetters(updated1);
updated1 = reverse(updated2);

for (int i = 0; i < updated2.length(); i++)
{
    if (updated2[i] != updated1[i])
    {
        break;
        return false;
    }
    else if (updated2[i] == updated1[i])
    {
        return true;
    }

}

}

  1. 删除break,如果字符不同,只返回false
  2. 不要在循环中return true——直到你看完所有字符,你才知道它是回文!相反,如果for循环结束,只需在循环外返回true即可

假设其他函数中没有错误,则将for循环更改为:

for (int i = 0; i < updated2.length(); i++)
{
    // If we find even one inequality, we know its not a palindrome.
    if (updated2[i] != updated1[i])
        return false;
}
// if the for loop has been executed satisfactorily, we know that it is a palindrome.
return true;

您不必反转字符串,只需要检查它是否是对称

bool testIt(const string value)
{ 
  string updated2 = makeLower(removeNonLetters(value));
  int L = updated2.length();
  for(var i = 0; i < L/2; i++)
  {
    if (updated2[i] != updated2[L-1-i])
      return false;
  }
  return true;
}

这不起作用的原因是在返回语句之前有一个break语句。这会中断循环,因此永远不会调用return。

可能的解决方案:

1) 删除"if not equal"情况下的break语句。2) 默认情况下,在函数末尾的循环外返回false。

编辑:

我还注意到,你是从"if is equal"的内部返回的。如果你这样做,那么它只会检查第一组字符。一个更好的算法是在"if not equal"的情况下返回false,删除"if equal",然后在函数末尾默认返回true。

在第一个ifreturn语句之前不应该有break,在第二个return true中也不应该有,因为您没有完成循环。

你可以这样做:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isnotalpha(char c){return !isalpha(c);}
int main(void) 
{
    string updated1="AbbA",updated2;
    transform(updated1.begin(),updated1.end(),updated1.begin(),tolower);
    updated1.erase(remove_if(updated1.begin(),updated1.end(),isnotalpha),updated1.end());
    updated2=updated1;
    reverse(updated2.begin(),updated2.end());
    bool palindrome=true;
    for(int i=0; i<updated1.length(); i++)
    {
        if(updated1[i]!=updated2[i]) palindrome=false;
        //if(updated1[i]!=updated1[updated1.length()-1-i]) palindrome=false; Can be done without using updated2
    }
    if(palindrome) cout << "Palindrome!" << endl;
    else cout << "Not Palindrome!" << endl;
    return 0;
}