C语言递归算法判断字符串是否为回文
递归判断字符串是否为回文
本文将介绍如何使用递归算法判断一个由字符数组存放的字符串 str 是否为回文。
递归模型
- 如果字符串长度为0或1,那么它一定是回文。
- 如果字符串首尾字符相同,那么判断去掉首尾字符的子串是否为回文。
- 如果字符串首尾字符不同,那么它一定不是回文。
递归程序
bool isPalindrome(char str[], int start, int end) {
if (start >= end) { // 如果字符串长度为0或1,那么它一定是回文。
return true;
}
if (str[start] == str[end]) { // 如果字符串首尾字符相同,那么判断去掉首尾字符的子串是否为回文。
return isPalindrome(str, start + 1, end - 1);
} else { // 如果字符串首尾字符不同,那么它一定不是回文。
return false;
}
}
调用方式
char str[] = 'abcba';
int len = strlen(str);
bool result = isPalindrome(str, 0, len - 1);
解释:
isPalindrome(char str[], int start, int end)函数接受三个参数:str: 字符数组,存储待判断的字符串。start: 字符串起始位置索引。end: 字符串结束位置索引。
- 函数首先判断
start是否大于等于end,如果是,说明字符串长度为0或1,返回true。 - 然后判断
str[start]和str[end]是否相等,如果相等,则递归调用isPalindrome函数,判断去掉首尾字符的子串是否为回文。 - 如果
str[start]和str[end]不相等,则直接返回false。
示例:
对于字符串 abcba,调用 isPalindrome(str, 0, 4),程序会进行如下判断:
start为 0,end为 4,str[start]和str[end]相等,递归调用isPalindrome(str, 1, 3)。start为 1,end为 3,str[start]和str[end]相等,递归调用isPalindrome(str, 2, 2)。start为 2,end为 2,start大于等于end,返回true。- 由于所有递归调用都返回
true,因此最终isPalindrome(str, 0, 4)返回true,说明abcba是回文。
该递归算法简单易懂,并且可以有效地判断字符串是否为回文。
原文地址: https://www.cveoy.top/t/topic/nm8h 著作权归作者所有。请勿转载和采集!