验证字符串是否为回文的函数
Function that verify's if the string is a palindrom
现在我正在编写一个程序,该程序告诉您输入的字符串是否为回文,而我正停留在最后一步。有三个基本函数可以删除句子中的所有空格,将它们降到小写,然后反转它们,然后我的函数验证它们,然后返回布尔值。所以现在在这个功能中,生日快乐!会以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;
}
}
}
- 删除
break
,如果字符不同,只返回false - 不要在循环中
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。
在第一个if
的return
语句之前不应该有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;
}
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- Usaco第1.6节主要回文
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 将 S1 转换为回文,并将 S2 作为其子字符串
- 数回文词
- 最长的回文子串(C++帮助)
- 回文过滤器,函数运行良好,但main()无法编译
- 寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文
- 为什么我的回文函数总是返回假
- 采用向量参数的函数模板回文
- 验证字符串是否为回文的函数
- 使用递归的回文函数
- 制作回文函数
- 用于识别回文字符数组的递归函数
- 这个递归函数(回文)变成了一个无限循环
- 使用不同的函数(C++)测试一个数字是否是回文
- C++回文函数
- c++函数中的回文返回false
- 带链表的回文函数
- c++回文Bool函数(使用指针)