同時從字符串頭尾開始向中間掃描字串,如果所有字符都一樣,那么這個字串就是一個回文。采用這種方法的話,我們只需要維護頭部和尾部兩個掃描指針即可。
代碼如下:
bool IsPalindrome(const char *s, int n)
{
// 非法輸入
if (s == NULL || n < 1)
{
return false;
}
const char* front,*back;
// 初始化頭指針和尾指針
front = s;
back = s+ n - 1;
while (front < back)
{
if (*front != *back)
{
return false;
}
++front;
--back;
}
return true;
}