定义两个指针,从两头开始同时向中间扫描字串:
bool IsPalindrome(const 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) return false;
++front;
--back;
}
return true;
}
定义两个指针,从中间开始,向两边扩展:
bool IsPalidrome(const char* s, int n) {
if(s == 0 || n < 0) return false;
char *first, *second;
int m = ((n >> 1) - 1) >= 0 ? (n >> 1) - 1 : 0;
first = s + m;
second = s + n - 1 - m;
while(first >= s) {
if(s[first--] != s[second++]) return false;
}
return true;
}
例题:找出字符串中最长的回文子串:
#include <iostream>
using namespace std;
int LongestPalindrome(const char* s, int n) {
int i, j, max;
if(s == 0 || n < 1) return 0;
max = 0;
for(i = 0; i < n; ++i) {
for(j = 0; (i - j >= 0) && (i + j < n); ++j) {
if(s[i - j] != s[i + j]) break;
}
if((j - 1) * 2 + 1 > max) max = (j - 1) * 2 + 1;
for(j = 0; (i - j >= 0) && (i + j + 1 < n); ++j) {
if(s[i - j] != s[i + j + 1]) break;
}
if((j - 1) * 2 + 2 > max) max = (j - 1) * 2 + 2;
}
return max;
}
int main() {
const char* s = "aaavfghhgfv";
int n = strlen(s);
cout<<LongestPalindrome(s,n)<<endl;
}