题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
// HJ85-3 最长回文子串.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 #include<iostream> #include<bits/stdc++.h> using namespace std; int check(string& s, int a) { int len = s.size(); int i = a, j = a + 1; while (i >= 0 && j <= len - 1) { if (s[i] == s[j]) { i--; j++; } else if(s[i]!=s[j]) { break; } } return j - i - 1; } int check2(string& s, int a) { int len = s.size(); int i = a-1, j = a + 1; while (i >= 0 && j <= len - 1) { if (s[i] == s[j]) { i--; j++; } else if (s[i] != s[j]) { break; } } return j - i - 1; } int main() { string s; while (cin >> s) { int ans = 1, res = 0; for (int i = 0; i < s.size(); i++) { int a=check(s, i); int b=check2(s, i); res = max(a, b); ans = max(res, ans); } cout << ans << endl; } return 0; }