c++ - 只有字符串作为输入的回文测试函数
问题描述
我正在尝试在 C++ 中编写一个递归函数来检查字符串是否为回文。(回文是一个字符串,其前后拼写方式与“radar”相同)
该函数必须是布尔值,并且只将字符串作为输入。
但它只适用于有两个字母的字符串。除此之外,它总是返回 1。
这是代码:
bool testPalindrome (string x) {
static int y = 1;
static int z = x.size();
if ((z - y == 1 || z - y == 2) && x[x.size() - z] == x[x.size() - y]) {
return true;
} else if (x[x.size() - z] == x[x.size() - y]) {
--z;
++y;
testPalindrome(x);
} else {
return false;
}
}
解决方案
这是一个更 C++ 惯用的解决方案
#include <iostream>
#include <string>
using namespace std;
bool testPalindrome(string inString)
{
if (inString.size() < 2)
return true;
else if (inString.front() != inString.back())
return false;
else
return (testPalindrome(inString.substr(1, inString.size() - 2)));
}
int main()
{
cout << testPalindrome("racecar") << endl;
cout << testPalindrome("race") << endl;
}
如果您使用 string_view 作为输入参数,效率会更高一些。
推荐阅读
- https - macOS Monterey 12.0.1 (Safari 15.1) 上的 SvelteKit - 在没有 https 的情况下在 localhost 上运行,但 Safari 尝试通过 https 加载资源
- java - 海我需要制作一个 Servlet 来接收用户名并在控制台中打印为“登录”。但它在我的代码中显示“登录失败”
- python - 如何将键的下一个值添加到字典中另一个键的上述值
- swift - 构建圆形金字塔 - SwiftUI
- css - ASP.NET Core MVC 如何动态添加主题支持是什么标准?
- python - 试图编写一个函数来找到 n 多个 6 面骰子的组合结果
- python - python中的回文函数,由老师的逻辑
- r - 我想使用 `summarise()` 来计算整个团队的最低、平均和最高工资
- html - 将 HTML 网站与 React 应用共享身份验证合并
- node.js - nrwl nx 节点角度版本兼容性