回文检查

一、判断一个整数是不是回文

bool IsPalindromeInt(int N)
{
     int reverse=0,rem,temp = N;
     while(temp!=0)
    { 
      rem=temp%10;
      reverse=reverse*10+rem; 
      temp/=10; 
    } 
      if(reverse==N) 
          printf("%d Is a palindrome.\n",N); 
      else 
          printf("%d is Not a palindrome.\n",N); 
}

二、判断一个字符串是不是回文

方法一:从字符串两头开始同时向中间扫描,如果直到相遇两端的字符都一样,则该字串就为一个回文。

方法二:从字符串中间开始、向两边扩展查看字符是否相等,若全部相等,则为回文。

//判断一个字符串是否为回文 ,方法一 
bool IsPalindrome1(char *s, int n)  
{  
   if (s == 0 || n < 1) return false; 
   char *front, *back;  
   front = s; back = s + n - 1; 
   while (front < back) 
   {  
       if (*front++ != *back--) 
       {
           cout<<"abcdcba is Not a palindrome."<<endl;
           return false; 
       }
   }  
   cout<<"abcdcba Is a palindrome."<<endl;
   return true;  
}  

// 方法二
bool IsPalindrome2(char *s, int n)  
{  
   if (s == 0 || n < 1) return false; 
   char *p, *q;  
   int m = n/2; // m 是字符串中点     
   p = s + m; q = s + n - 1 - m;  
   while (p >= s)
   {  
       if (*p-- != *q++)
       {
           cout<<"abcdcba is Not a palindrome."<<endl;
           return false; 
       }
   }
   cout<<"abcdcba Is a palindrome."<<endl;
   return true; 
}   

三、求一个字符串中的最长回文子串长度

我们可以枚举中心位置,再向两边扩展查看字符是否相等,记录并更新得到的最长的回文长度。

//求一个字符串中的最长回文子串
int MaxPalindrome(char *s, int n)  
{  
   int i, j, max;  
   if (s == 0 || n < 1) return 0;  
   max = 0;  
   for (i = 0; i < n; ++i) { // i是回文的中点  
       for (j = 0; (i-j >= 0) && (i+j < n); ++j) // 如果回文长度为奇数  
           if (s[i-j] != s[i+j]) break;  
       if (j*2+1 > max) 
           max = j * 2 + 1;  
       for (j = 0; (i-j >= 0) && (i+j+1 < n); ++j) // 如果回文长度为偶数 
           if (s[i-j] != s[i+j+1]) break;  
       if (j*2+2 > max) 
           max = j * 2 + 2;  
    } 
   printf("最长回文长度为:%d \n",max); 
   return max;  
}  

测试函数

#include <iostream>
using namespace std;

int main() 
{ 
    bool IsPalindromeInt(int N);
    bool IsPalindrome1(char *s, int n);
    bool IsPalindrome2(char *s, int n);  
    int MaxPalindrome(char *s, int n);
    
    int N = 12321;
    char s[] = "abcdcba";
    int n = 7;
    char s1[] = "acStringgnirtSbcb";
    int n1 = 18; 
    IsPalindromeInt(N);
    IsPalindrome1(s, n);
    IsPalindrome2(s, n);
    MaxPalindrome(s1, n1);
    system("pause");
    return 0;
}




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值