首页 > 解决方案 > 只有字符串作为输入的回文测试函数

问题描述

我正在尝试在 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++

解决方案


这是一个更 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 作为输入参数,效率会更高一些。


推荐阅读