C++ 中檢查字串是否為迴文數的遞迴函式


給定一個字串 Str 作為輸入。目標是使用遞迴函式查詢輸入字串是否為迴文詞。迴文串是指從前向後或從後向前讀取形成相同單詞的字串。長度為 0 的字串被認為是迴文串。反轉回文串的字元會形成與原始字串相同的字串。

迴文串的例子:- madam、abcba、malayalam 等

示例

輸入 - Str = “malayalam”

輸出 - 輸入字串是迴文串。

解釋 -

Str[ 0 到 8 ] = malayalam

反轉 Str [ 8 到 0 ] = malayalam

兩個字串相同。

輸入 - Str = “tutorial”

輸出 - 輸入字串不是迴文串。

解釋 -

Str[ 0 到 7 ] = tutorial

反轉 Str [ 7 到 0 ] = lairotut

兩個字串不同

下面程式中使用的方法如下

在這種方法中,我們將檢查字串是否包含單個字元,如果為真,則它是迴文串。如果不是,則遞迴遍歷整個字串以獲取其餘字元,並在對應字元不同時中斷遞迴。

  • 獲取輸入字串 Str[] 並計算其長度。

  • 如果長度為 0,則設定 result=1。

  • 否則設定 result=checkPalindrome(Str, 0, length - 1),其中 0 是第一個索引,length - 1 是最後一個索引

  • 函式 checkPalindrome(char str[], int first, int last) 如果任何字元與其在字串中的對應字元不匹配,則返回 0。

  • 如果索引 first 和 last 相同,則字串只有一個字元,然後返回 1。

  • 如果不是,則檢查除結束字元之外的其餘字元,方法是 first++,last-- 並遞迴呼叫 checkPalindrome(str, first, last)。

  • 在所有遞迴結束時,我們將獲得一個結果。

  • 如果它是 1,則輸入字串是迴文串。

  • 否則輸入字串不是迴文串。

  • 在 main 中列印結果。

示例

#include <bits/stdc++.h>
using namespace std;
int checkPalindrome(char str[], int first, int last){
   if (first < last + 1){
      first++;
      last--;
      return checkPalindrome(str, first, last);
   }

   if (first == last){
      return 1;
   }
   if (str[first] != str[last]){
      return 0;
   }
   return 1;
}
// Driver Code
int main(){
   char Str[] = "madam";
   int result;
   int length = strlen(Str);
   if (length == 0){
      result=1;
   }

   else{
      result=checkPalindrome(Str, 0, length - 1);
   }
   if (result==1){
      cout << "Input string is palindrome.";
   }
   else{
      cout << "Input string is not a palindrome.";
   }
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

Input string is palindrome.

更新於: 2021年11月2日

6K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告