Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชันเรียกซ้ำตรวจสอบสตริง Palindrome ใน C++

ภาพรวม

ได้รับสตริง Str เป็นอินพุต เป้าหมายคือตรวจสอบว่าเป็นคำ Palindrome (อ่านจากหน้าหลังได้เหมือนกัน) หรือไม่ โดยใช้ฟังก์ชันเรียกซ้ำ สตริงความยาว 0 ถือว่าเป็น Palindrome การกลับลำดับตัวอักษรของ Palindrome จะได้สตริงเดิม ตัวอย่าง: madam, abcba, malayalam

ตัวอย่าง

อินพุต − Str = "malayalam"

เอาต์พุต − Input string is palindrome.

คำอธิบาย −

Str[0..8] = malayalam

Reverse Str[8..0] = malayalam

ทั้งสองสตริงเหมือนกัน

อินพุต − Str = "tutorial"

เอาต์พุต − Input string is not a palindrome.

คำอธิบาย −

Str[0..7] = tutorial

Reverse Str[7..0] = lairotut

ทั้งสองสตริงต่างกัน

แนวทางการแก้ปัญหา

ตรวจสอบว่าสตริงมีตัวอักษรเดียวหรือไม่ หากใช่ คือ Palindrome มิฉะนั้น เรียกซ้ำตรวจสอบตัวอักษรที่เหลือ หยุดการเรียกซ้ำหากตัวอักษรที่ตรงกันไม่เหมือนกัน

  • รับสตริง Str[] คำนวณความยาว
  • หากความยาว 0 ตั้ง result = 1
  • มิฉะนั้น result = checkPalindrome(Str, 0, length-1) โดย 0 คือดัชนีแรก length-1 คือดัชนีสุดท้าย
  • ฟังก์ชัน checkPalindrome(char str[], int first, int last) คืน 0 หากตัวอักษรไม่ตรง
  • หาก first == last คืน 1 (เหลือตัวอักษรเดียว)
  • หาก str[first] != str[last] คืน 0
  • มิฉะนั้น เรียกซ้ำ checkPalindrome(str, first+1, last-1)
  • พิมพ์ผลลัพธ์ใน main

ตัวอย่างโค้ด C++

#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; 
} 

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.