递归判断一个字符串是否回文

回文:例如123321,12321这样的。

那么如何判断一个字符串是否是回文呢?

以下用两种方法解决这个问题。

第一种,用循环。代码如下:

bool IsPalindereme(char* str,int size)
 {
	
   int begin=0;//字符串第一个下标
   int end=size-1;//字符串最后一个下标
   while(begin<end)
   {
      if(str[begin]!=str[end])
           return false;
      begin++;
      end--;
   
   }
   return true;
}
第二种呢,用递归实现。

bool IsPalindereme(char* str,int size)
 {
  //递归
	 if(size<=1)
		 return true;
	 if(str[0]!=str[size-1])
		 return false;
	 else
       return IsPalindereme(++str,size-2);
 }




在C语言判断一个字符串是否回文串可以通过两种常见的方法实现: 1. **双指针法**:这是一种常用的迭代方法,创建两个指针,一个指向字符串的开始(i),另一个指向结束(j)。然后逐个比较对应的字符,如果它们相等则继续向间移动,如果不相等则说明不是回文串。当两个指针相遇或者交叉时,都没有发现不相等的字符,则该字符串回文串。 ```c #include <stdio.h> #include <string.h> int isPalindrome(char str[]) { int i = 0, j = strlen(str) - 1; while (i < j) { if (str[i] != str[j]) return 0; // 回文串不成立 i++; j--; } return 1; // 字符串回文串 } int main() { char test[] = "madam"; if (isPalindrome(test)) printf("%s 是回文串\n", test); else printf("%s 不是回文串\n", test); return 0; } ``` 2. **递归法**:另一种方法是递归地比较字符串的第一个字符和最后一个字符,然后递归检查剩下的部分。如果所有对应位置的字符都相等,那么整个字符串就是回文串。 ```c #include <stdbool.h> #include <string.h> bool isPalindromeRec(char str[], int start, int end) { if (start >= end) return true; if (str[start] != str[end]) return false; return isPalindromeRec(str, start + 1, end - 1); } // 调用示例 bool isPalindromeCharByChar(const char* str) { return isPalindromeRec(str, 0, strlen(str) - 1); } int main() { if (isPalindromeCharByChar("madam")) printf("madam 是回文串\n"); else printf("madam 不是回文串\n"); return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值