palindrome.cpp
来自「BigC++的源码」· C++ 代码 · 共 41 行
CPP
41 行
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
Tests whether a string is a palindrome. A palindrome
is equal to its reverse, for example "rotor" or "racecar".
@param s a string
@return true if s is a palindrome
*/
bool is_palindrome(string s)
{
// separate case for shortest strings
if (s.length() <= 1) return true;
// get first and last character, converted to lowercase
char first = s[0];
char last = s[s.length() - 1];
if (first == last)
{
string shorter = s.substr(1, s.length() - 2);
return is_palindrome(shorter);
}
else
return false;
}
int main()
{
cout << "Enter a string: ";
string input;
getline(cin, input);
cout << input << " is ";
if (!is_palindrome(input)) cout << "not ";
cout << "a palindrome.\n";
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?