简体   繁体   English

C递归检查回文

[英]C Recursively checking a Palindrome

I've got an assignment where I need to check if a given string is a palindrome or not recursively. 我有一个作业,我需要检查给定的字符串是回文还是不是递归的。

EG : EG:

aD1Da // returns 1
asd1s // returns 0

The function signature needs to look like this: 函数签名应如下所示:

int isPolindrom(char str[]);

Which means I'm getting only one parameter. 这意味着我只得到一个参数。 I managed to build a solution using a static variable (The function will be called more than once, so we were instructed not to use static variables, though my solution works for more than 1 call). 我设法使用静态变量构建了一个解决方案(该函数将被多次调用,因此,尽管我的解决方案可以调用多次,但仍指示我们不要使用静态变量)。

My solution: 我的解决方案:

static flag = 0; 
int isPolindrom(char str[])
{
    static int pos = 1;
    if (flag == 1) { 
        pos = 1; // Reset
        flag = 0; // Reset
    }
    if (pos >= strlen(str)) { 
        flag = 1; 
        return 1; 
    }
    if (*str == *(str + strlen(str) - pos)) { 
        pos++; 
        return  isPolindrom(str + 1); 
    }
    else return 0; 
}

It's also possible using a secondary function, but I was wondering if and how is it possible to do this without static variables and without writing secondary functions. 也可以使用辅助函数,但是我想知道是否以及如何在没有静态变量且没有编写辅助函数的情况下做到这一点。

In the automatic tests they are sending me the string as a constant string. 在自动测试中,他们将字符串作为常量字符串发送给我。 For example: 例如:

isPolindrom("abcba")

Yes it is possible. 对的,这是可能的。 Assuming that string is null terminated and is mutable we will do this 假设字符串以null终止并且是可变的,我们将这样做

int isPolindrom(char s[])
{

    int l = 0;
    while(s[l]) l++;
    if(l == 2)
       return s[0]==s[1];
    if(l <= 1)
       return 1;

    char c=s[l-1];
    s[l-1]=0;

    int result = (s[0]==c) && isPolindrom(s+1);

    s[l-2]=c;
    return result ;
}

Though it doesn't change the passed argument - we are modifying it internally. 尽管它不会更改传递的参数-我们正在内部对其进行修改。 That's why modifiable sting requirement was needed. 这就是为什么需要可修改的刺痛要求的原因。

After edit: 编辑后:

Note my earlier answer was considering that you couldn't use any function but as OP made it clear we can easily use standard library functions like malloc etc. That's why this solution using dynamically allocated memory. 请注意,我之前的回答是考虑您不能使用任何函数,但是正如OP所表明的那样,我们可以轻松使用malloc等标准库函数。这就是为什么此解决方案使用动态分配的内存。

With the given constraint 在给定的约束下

int isPolindrom(const char *s)
{
    int l = 0;
    while(s[l]) l++;
    if(l == 2)
      return s[0]==s[1];
    if(l == 1)
      return 1;

    char *ss =  malloc(l-1);
    if( ss == NULL ){
       perror("Error in malloc");
       exit(EXIT_FAILURE);
    }
    for(int i=0;i<l-2;i++)
    ss[i]=s[i+1];
    ss[l-2]=0;
    int p = (s[0]==s[l-1]) && isPolindrom(ss);

    free(ss);
    return p;
}

Creating a new string inside palindrome() . palindrome()创建一个新字符串。

int palindrome(char *str)
{ 
    int len= strlen(str);
    if(len<=1)
      return true;
    char a=str[0];
    char b=str[len-1];
    char *newstr=malloc(len-2+1);
    for(int i=1;i<len-1;i++)
        newstr[i-1] = str[i];
    newstr[len-2]='\0';

    int res = (a==b && palindrome(newstr));
    free(newstr);
    return res;
}

and call it as 并称其为

 palin("abcba");

This is my take on this: 这是我的看法:

  1. check if string must be palindrome (ie less than 2 chars), if yes - return true 检查字符串是否必须是回文(即少于2个字符),如果是,则返回true
  2. if no, check if first == last , if yes - recursive call with the inner string 如果否,请检查first == last ,如果是-使用内部字符串进行递归调用

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

bool is_palindrome(char * str){
    // end conditions
    if (!str)
        return false;
    if (strlen(str) < 2)
        return true;

    // check first vs. last
    if (str[0] == str[strlen(str) - 1]){
        // remove first & last chars (copy to array to allow this)
        char tmp_arr[strlen(str) - 1];
        strncpy(tmp_arr, str+1, strlen(str) - 2);
        tmp_arr[strlen(str) - 2] = '\0';
        return is_palindrome(tmp_arr);

        /* if string was mutable - this would be easier:

                str[strlen(str) - 1] = '\0';
                return is_palindrome(str + 1);
        */
    }

    return false;
}

int main(){
    printf(is_palindrome("abcddcba") ? "true\n" : "false\n");
    printf(is_palindrome("abcddcbaa") ? "true\n" : "false\n");
    printf(is_palindrome("abcd   dcba") ? "true\n" : "false\n");
    while(1);
    return 0;
}

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

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