判断回文串

判断回文串C++实现

回文串:level、abba
非回文串:hevel、aabb

方法解析:
1. 首先得知道字符数组的长度(要么使用现成的计算字符数组长度的函数,要么自己写一个遍历区数,都得花费O(n)时间,暂时没有能够节省这部分时间的方法)
2. 然后就从中间的字符开始,往两边走,两边各取一个元素比较,若不相等则跳出,得到答案是这个是非回文串,若相等则继续往两边走,以此类推。
3. 可以用压栈的形式,但其实没啥必要,还徒增stack空间,而且一样要事先遍历一边数大小。既然是char数组,直接用下表操作即可。

C++代码:

#include <iostream>
#include <cstring>
using namespace std;

//判断字符数组是否为回文串 
bool palindrome(char *s)
{
    if(s == NULL)
        return false;
    int len = strlen(s);
    int left, right;
    if(len % 2 == 0) //len为偶数 
    {
        left = len / 2 - 1; 
        right = len / 2;
    }
    else
    {
        left = len / 2 - 1; 
        right = len / 2 + 1;
    }
    for(;(left >= 0) && (right < len); left--, right++) //注意循环的边界条件 
    {
        if(s[left] != s[right])
            return false;
    }
    return true;
}

int main()
{
    //char数组很特殊,需要给''预留一个位置 
    char *s;
    cin>>s;
    bool result = palindrome(s);
    if(result == true)
        cout<<"是回文串"<<endl;
    else
        cout<<"不是回文串"<<endl;

    return 0;
}
原文地址:https://www.cnblogs.com/lvlang/p/10586392.html