大三总结

编写一个程序判断一个字符串是否是回文。回文是指一个字符序列以中间字符为基准两边字符完全相同,如字符序列"ABCDEDCBA"就是回文,而字符序列"ABCDEDBAC"就不是回文。

include

include

bool isPalindrome(const std::string& str) {
int left = 0;
int right = str.length() - 1;

while (left < right) {
// 忽略左边的空格
while (left < right && str[left] == ' ') {
left++;
}
// 忽略右边的空格
while (left < right && str[right] == ' ') {
right--;
}

// 比较非空格字符
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}

return true;
}

int main() {
std::string input;
std::getline(std::cin, input); // 读取整个输入行,包括空格

if (isPalindrome(input)) {
std::cout << "该字符串是回文字符串" << std::endl;
} else {
std::cout << "该字符串不是回文字符串" << std::endl;
}

return 0;
}

posted @ 2026-01-09 14:04  C(5,3)  阅读(7)  评论(0)    收藏  举报