繁体   English   中英

如何让这个递归函数检查字符串是否是回文?

[英]How to make this recursive function check if the string is a palindrome?

该函数应该反转字符串,如果前后相同,则返回 true。 我必须为此使用递归,而不能为此使用reverse() 我通过调试器运行了我的代码,似乎我的代码在检查 s == reverse 时返回 false。

这是我的尝试:

bool Palindrome(const string& s, int i){
string reverse;

    if(i < s.size()){
        reverse[i] = s[s.size()-(i+1)]; // first character in reverse is the last character in s
        Palindrome(s, i + 1);
        }       
    if(s == reverse){
        return true;
    }
    else{
        return false;
    }

}

以下代码显示了您在问题中阐述的内容的示例实现。 它使用递归创建一个反向字符串,然后将其与参考字符串进行比较,并返回一个布尔结果。

内存复杂度 O(n)。 但实际上,反转字符串确实需要额外的 O(n) 内存。

#include <iostream>
#include <algorithm>
using namespace std;

bool isPalindrome(string& reference, string& reversed, int index){
    if(index >= reference.size()/2){
        return reference == reversed;
    }

    int lastIndex = reference.size()-1;
    swap(reversed[index], reversed[lastIndex-index]);
    return isPalindrome(reference, reversed, index+1);
}

int main() {
    string ref = "abcdcba";
    string test = ref;
    cout << isPalindrome(ref,test,0) << endl;
    return 0;
}

如果您希望Palindrome(const string&)操作string reverse您应该通过引用传递它。

#include <string>
#include <iostream>

using namespace std;

bool palindrome_internal( const string& s, string& reverse, int i )
{
    if(i < s.size()){
        reverse[i] = s[s.size()-(i+1)]; // first character in reverse is the last character in s
        palindrome_internal( s , reverse , i + 1);
    }

    return s == reverse;
}

bool Palindrome(const string& s ){
    string reversed { s }; // initialized here

    return palindrome_internal( s , reversed , 0 ); // And passed to recursive function
}

int main()
{
    cout << Palindrome( "example" ) << endl; // Not palindrome
    cout << Palindrome( "repaper" ) << endl; // Palindrome
    cout << Palindrome( "rotator" ) << endl; // Palindrome
    cout << Palindrome( "madam" ) << endl; // Palindrome
    cout << Palindrome( "" ) << endl; // Palindrome
    cout << Palindrome( "" ) << endl; // Palindrome
}

在线代码

你的代码实际上有点奇怪,因为你不是递归地计算回文,实际上你是递归地填充string reverse

也许这个更简单的版本更适合。

#include <string>
#include <iostream>

bool palindrome( const std::string& s, int i = 0 )
{
    if ( i == s.size() )
        return true;

    return s[ i ] == s[ s.size() - i - 1 ] && palindrome( s , i + 1 );
}

int main()
{
    using namespace std;
    cout << palindrome( "example" ) << endl; // Not palindrome
    cout << palindrome( "repaper" ) << endl; // Palindrome
    cout << palindrome( "rotator" ) << endl; // Palindrome
    cout << palindrome( "madam" ) << endl; // Palindrome
    cout << palindrome( "" ) << endl; // Palindrome
    cout << palindrome( "a" ) << endl; // Palindrome
}

在线代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM