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