回文判断

来源:互联网 发布:标书软件 编辑:程序博客网 时间:2024/05/23 12:01

说明:转载请标明出处http://blog.csdn.net/yuanwei1314/article/details/40792731

题目:

 回文,英文palindrome,指一个顺着读和反过来读都一样的字符串,比如madam、我爱我,这样的短句在智力性、趣味性和艺术性上都颇有特色,中国历史上还有很多有趣的回文诗。

那么,我们的第一个问题就是:判断一个字串是否是回文?

 

思路一:从两头比较,时间复杂度O(n),空间复杂度O(1)

 

#include <stdio.h>#include <stdlib.h>/*判断字符串是否为回文  从两边往中间比较*/bool isPalindrome(char *s, int n){    int high = n-1;    int low = 0;    while (low < high)    {        if (*(s+low) != *(s+high))        {            return false;        }        low++;        high--;    }    return true;}int main(){    char s[] = "madam";    if (isPalindrome(s, strlen(s)))    {        printf("true\n");    }    else    {        printf("false\n");    }    return 0;}

思路二:从中间往两头比较,时间复杂度O(n),空间复杂度O(1)

#include <stdio.h>#include <stdlib.h>/*判断字符串是否为回文  从中间往两边比较*/bool isPalindrome(char *s, int n){    int high;    int low;    if (n%2 != 0)    {        high = n/2+1;        low = n/2-1;    }    else    {        high = n/2;        low = n/2-1;    }        while (low>0 && high<n)    {        if (*(s+low) != *(s+high))        {            return false;        }        low--;        high++;    }    return true;}int main(){    char s[] = "madddam";    if (isPalindrome(s, strlen(s)))    {        printf("true\n");    }    else    {        printf("false\n");    }    return 0;}


0 0