回文判断

说明:转载请标明出处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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值