递归判断字符串是否为回文

本文将介绍如何使用递归算法判断一个由字符数组存放的字符串 str 是否为回文。

递归模型

  1. 如果字符串长度为0或1,那么它一定是回文。
  2. 如果字符串首尾字符相同,那么判断去掉首尾字符的子串是否为回文。
  3. 如果字符串首尾字符不同,那么它一定不是回文。

递归程序

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),程序会进行如下判断:

  1. start 为 0,end 为 4,str[start]str[end] 相等,递归调用 isPalindrome(str, 1, 3)
  2. start 为 1,end 为 3,str[start]str[end] 相等,递归调用 isPalindrome(str, 2, 2)
  3. start 为 2,end 为 2,start 大于等于 end,返回 true
  4. 由于所有递归调用都返回 true,因此最终 isPalindrome(str, 0, 4) 返回 true,说明 abcba 是回文。

该递归算法简单易懂,并且可以有效地判断字符串是否为回文。


原文地址: https://www.cveoy.top/t/topic/nm8h 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录