简体   繁体   中英

Data structure and algorithm(C++)

A palindrome is a phrase that reads the same forward and backward (examples: 'racecar', 'radar', 'noon', or 'rats live on no evil star'). By extension we call every string a palindrome that reads the same from left to right and from right to left. Develop a recursive algorithm that takes as input a string and decides whether the string is a palindrome. Implement your algorithm in the PalindromeChecker(String) method.

#include <iostream>
#include <string>

using namespace std;

bool isPolindrom(string s){
  int len = s.length();
  if (len < 2) return true; // if s == '' or s == <one symbol>   
  bool condition = (s[0] == s[len-1]); // first symbol == last symbol
  return condition && isPolindrom(s.substr(1, len-2)); // recursion
} 

int main()
{
  string name;
  cout << "What is your word? ";
  getline (cin, word);
  cout << "it is" << (isPolindrom(word) ? " polindrom" : " not polindrom"); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM