什么是回文?
回文是一种特殊的字符串,无论从左向右读还是从右向左读,都是相同的。例如,"aba"和"aabaa"都是回文字符串。
问题描述
我们的任务是编写一个C++程序,接受用户输入的字符串,然后判断该字符串是否是回文。如果是回文,输出"yes";否则,输出"no"。
解决方案
#include <iostream>
#include <string>
using namespace std;
// 函数声明
bool isPalindrome(const string& str);
int main() {
// 输入字符串
cout << "请输入一个字符串(长度不超过100): ";
string input;
cin >> input;
// 调用函数判断是否是回文
if (isPalindrome(input)) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
return 0;
}
// 函数定义:判断字符串是否是回文
bool isPalindrome(const string& str) {
// 获取字符串长度
int length = str.length();
// 逐个比较字符是否对称
for (int i = 0; i < length / 2; ++i) {
if (str[i] != str[length - 1 - i]) {
return false; // 不对称,不是回文
}
}
return true; // 完全对称,是回文
}