找Palindrome

时间:2017-01-18 15:20:05

标签: c++ string function recursion palindrome

我想找一个单词的回文。这里有什么不对吗?

主要功能:

  int size;
  string input;
  cin>>input;
  size = input.length();  
  if(testPalindrome(input,size-1,0))
    cout<<"It's Palindrome";
  else
    cout<<"It's not Palindrome";

testPalindrome函数是:

bool testPalindrome (string pal , int last, int first){

    if (pal[first] != pal[last])
        return false;
    else{
        if (first<last)
            testPalindrome(pal,last-1,first+1);
        else
            return true;
    }
}

我已阅读this link并找到了确定回文的答案,但为什么这个不起作用?

2 个答案:

答案 0 :(得分:6)

您需要返回递归调用的结果,就像调用任何其他函数一样。

如果不这样做,则行为未定义。

答案 1 :(得分:2)

我认为你忘记了函数

中的return语句
    if (first<last)
        return testPalindrome(pal,last-1,first+1);
        ^^^^^^^

通常,范围的第一个参数指定较低的值,第二个参数指定范围中未包含的范围的较高值或序列中的元素数。

第一个参数应声明为具有常量引用类型,因为字符串本身不会更改,您将转义额外的内存分配。

递归函数可以写成

#include <iostream>
#include <string>

bool testPalindrome(const std::string &s,
    std::string::size_type i,
    std::string::size_type n)
{
    return n < 2 || (s[i] == s[n-1] && testPalindrome(s, i + 1, n - 2) );
}

int main()
{
    std::cout << testPalindrome("abba", 0, 4) << std::endl;
    std::cout << testPalindrome("aba", 0, 3) << std::endl;
    std::cout << testPalindrome("aa", 0, 2) << std::endl;
    std::cout << testPalindrome("a", 0, 1) << std::endl;
    std::cout << testPalindrome("ab", 0, 2) << std::endl;

    return 0;
}

程序输出

1
1
1
1
0

检查std::string类型的对象是否是回文的最简单方法是编写表达式

s == std::string( s.rbegin(), s.rend() )