判断字符串是否为回文

GitHub跳转原题关系图返回列表

回文即正读与倒读相同;用双指针从两端向中间比较字符,遇到不等立即判否,全部配对成功则是回文。

OJ: roj

题目 ID: 1146

难度:入门

标签:入门字符串回文python

创建: 2026-09-29 20:49

更新: 2026-10-05 03:27

题目描述

输入一字符串(无空白,长度 ≤ 100),判断它正读与倒读是否相同:是则输出 yes,否则输出 no。

样例输入:abcdedcba → 样例输出:yes。

思路

用双指针从字符串两端向中间扫,每步比较两指针字符,相等则继续向内收缩,否则不是回文;扫到 i >= j 时所有对称位都配对成功,即为回文。整体 O(n)O(n)、O(1)O(1) 额外空间,n ≤ 100 完全够用。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 20:49
# update_at: 2026-09-29 20:49

import sys


def solve() -> None:
    text = sys.stdin.read().strip()   # 整行即整串,题面保证串内没有空白字符
    mirrored = text[::-1]             # 一次切片反转,倒读串由 C 层循环生成
    same = text == mirrored           # 回文 ⟺ 正读与倒读逐位相同
    print("yes" if same else "no")


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-05 03:27
 * update_at: 2026-10-05 03:27
 */

// main.cpp:判断字符串是否为回文。输入一整行字符串(无空白),输出 yes / no。
// 做法:双指针从两端向中间扫描,逐对比较字符,任何一对不等则不是回文。

#include <cstring>
#include <iostream>

using namespace std;

typedef long long ll;

const ll MAXN = 105;

char s[MAXN]; // 存读入的字符串(题面 n ≤ 100,开 105 留余)
ll n;         // 字符串实际长度

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // 读入一整行;题面保证串内没有空白字符,所以 cin >> s 即可。
    cin >> s;
    n = strlen(s);

    // 双指针 i、j 从两端向中间收缩,逐对比较字符是否相等。
    ll i = 0, j = n - 1;
    while (i < j && s[i] == s[j]) {
        i++;
        j--;
    }

    // i >= j 表示所有对称位都配对成功,是回文;否则不是。
    if (i >= j)
        cout << "yes\n";
    else
        cout << "no\n";

    return 0;
}