回文写法

本文介绍了一种检测字符串是否为回文串的算法,并考虑了忽略大小写及标点符号的情况。提供了完整的C/C++代码实现,包括如何去除源字符串中的标点符号,以及比较字符大小写不敏感的方法。

测试字符串是否是回文字串

   1. bool is_palindrome(char *str, int size)  
   2. {  
   3.    int tmp1 = size-2, tmp2 = (size-1)/2;  
   4.    for (int i = 0; i < tmp2; ++i)  
   5.    {  
   6.        if (str[i] != str[tmp1-i])  
   7.          return false;  
   8.    }  
   9.    return true;  
  10. }  

然后,不管对应位置的大小写:

可以这么写:

# bool is_palindrome(char *str, int size)  
# {  
#    int tmp1 = size-2, tmp2 = (size-1)/2;  
#    for (int i = 0; i < tmp2; ++i)  
#    {  
#        int char_dif = str[i]-str[tmp1-i];  
#        if (str[i] == str[tmp1-i] || abs(char_dif)==32)  
#          continue;  
#        return false;  
#    }  
#    return true;  
# } 

忽略源字符串内的标点符号,测试是否是回文串:

# #include <iostream>
# #include
<iostream>
# #include
<math.h>
#
using namespace std;
#
#
#
struct res
# {
#
char *s;
#
int size;
# };
# res ignore_punctuate(
char *str, int size)
# {
#
int tmp = size-2;
#
char *str1 = new char[size];
#
int j = 0;
#
for (int i = 0; i <= tmp; ++i)
# {
#
if (!ispunct(str[i]))
# {
# str1[j
++]=str[i];
# }
# }
# str1[j]
='\0';
# res tmp1;
# tmp1.s
= str1;
# tmp1.size
=j+1;
#
return tmp1;
# }
#
bool is_palindrome(char *str, int size)
# {
#
int tmp1 = size-2, tmp2 = (size-1)/2;
#
for (int i = 0; i < tmp2; ++i)
# {
#
int char_dif = str[i]-str[tmp1-i];
#
if (str[i] == str[tmp1-i] || abs(char_dif)==32)
#
continue;
#
return false;
# }
#
return true;
# }
#
#
int main()
# {
#
char a[]="abb,A";
#
int size = sizeof(a)/sizeof(*a);
# res tmp
= ignore_punctuate(a,size);
# cout
<< is_palindrome(tmp.s, tmp.size) << endl;
# }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值