【问题标题】:Data structure and algorithm(C++)数据结构与算法(C++)
【发布时间】:2021-01-02 19:14:22
【问题描述】:

回文是前后读相同的短语(例如:“racecar”、“radar”、 “中午”或“老鼠住在没有邪恶的星星上”)。通过扩展,我们将每个字符串称为回文,读取 从左到右和从右到左都一样。开发一个递归算法,将 a 作为输入 string 并确定该字符串是否为回文。在 PalindromeChecker(String) 方法。

【问题讨论】:

标签: c++ algorithm recursion palindrome


【解决方案1】:
#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"); 
}

【讨论】: