面试题:给定一个字符串,问是否能通过添加一个字母将其变为回文串

#include
#include
#include<string.h>
#define char_len 16

int huiwen(char str[])
{
        int str_len=strlen(str);
        int yushu=str_len%2;
        int mid_left,mid_right;
        if(yushu==1)
                mid_left=mid_right=str_len/2;
        else
        {
                mid_left=str_len/2-1;
                mid_right=str_len/2;
        }
        int i;
        char *p_left;
        char *p_right;
        if(yushu==1)
        {
                p_left=str+mid_left-1;
                p_right=str+mid_right+1;
        }
        else
        {
                p_left=str+mid_left;
                p_right=str+mid_right;
        }
        while(p_left>=str&&p_right<=str+str_len-1)
        {
                if(*p_left==*p_right)
                {
                        --p_left;
                        ++p_right;
                }
                else
                        return -1;
        }
        return 1;

}
int remove_char(char str[],int str_len,int index_remove,char dst_str[])
{
        int i=0,j;
                                              for(i=0,j=0;j)
        {
                if(i==index_remove)
                {
                        j+=1;
                }
                dst_str[i]=str[j];
        }
        dst_str[i]='\0';
        return 0;
}
int judge_huiwen(char str[])
{
        int str_len=strlen(str);
        int i=0;
        for(i=-1;i)
        {
                char dst_str[char_len]={'0'};
                remove_char(str,str_len,i,dst_str);
                int ret=huiwen(dst_str);
                if(ret==1)
                {
                        printf("YES\n");
                        return 0;
                }

        }
        printf("NO\n");
        return -1;
}

int main()
{
        char str[char_len];
        printf("please input a string:\n");
        gets(str);
        judge_huiwen(str);

}

思路是通过删除字符,判断是不是回文 ( 或反转字符串,再比较)

转载于:https://www.cnblogs.com/woshare/p/6937665.html

你可能感兴趣的:(面试题:给定一个字符串,问是否能通过添加一个字母将其变为回文串)