洛谷 B2124:判断字符串是否为回文 ← 双指针

📅 发布时间:2026/7/10 1:23:02 👁️ 浏览次数:
洛谷 B2124:判断字符串是否为回文 ← 双指针
【题目来源】https://www.luogu.com.cn/problem/B2124【题目描述】输入一个字符串输出该字符串是否回文。回文是指顺读和倒读都一样的字符串。【输入格式】输入一行字符串长度小于 100。【输出格式】如果字符串是回文输出 yes否则输出 no。【输入样例】abcdedcba【输出样例】yes​​​​​​​【算法分析】● 双指针算法的核心思想双指针算法的本质是用两个指针索引在一个 / 多个序列数组、字符串、链表中移动通过指针的 “同向 / 反向 / 相向” 移动替代暴力枚举的嵌套循环将时间复杂度从 O (n²) 优化到 O (n)。● 本题简单的方法是利用函数reverse(s.begin(),s.end());对字符串 s 进行回文判断。●​​​​​​​ 本题利用栈求解的代码详见https://blog.csdn.net/hnjzsyjyj/article/details/145522672【算法代码一双指针】#include bits/stdc.h using namespace std; int main() { string s; cins; int i0,js.size()-1; while(ij) { if(s[i]s[j]) i,j--; else { coutno; return 0; } } coutyes; return 0; } /* in:abcdedcba out:yes */【算法代码二reverse】#include bits/stdc.h using namespace std; int main() { string s,t; cins; ts; reverse(s.begin(),s.end()); if(st) coutyesendl; else coutnoendl; return 0; } /* in:abcdedcba out:yes */【参考文献】https://blog.csdn.net/hnjzsyjyj/article/details/145522672https://www.ituring.com.cn/book/tupubarticle/29874https://www.luogu.com.cn/problem/solution/B2124https://blog.csdn.net/hnjzsyjyj/article/details/126890655https://www.cnblogs.com/rabbit1103/p/9620373.html