一、判断一个整数是不是回文
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;
}