最长的回文子串是哪一段

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

一个字符串 abcbdcba(8 个字符)。回文就是正着读和倒着读一样。

运行下面这段程序:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

const string S = "abcbdcba";

string longest_pal_substr(const string& s) {
    string best;
    for (int i = 0; i < (int)s.size(); i++) {
        for (int j = i + 1; j <= (int)s.size(); j++) {
            string w = s.substr(i, j - i);
            if (w == string(w.rbegin(), w.rend()) && w.size() > best.size()) best = w;
        }
    }
    return best;
}

int main() {
    cout << longest_pal_substr(S) << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论