题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
利用扩散方法,贪心,分奇偶性讨论
只关注起始值left和步长step,迭代一次就扩大一次
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param A string字符串 * @return int整型 */ int getLongestPalindrome(string A) { // write code here int n = A.size(); int maxLen = 1; int step = 2; for(int left=0; left+step<=n; left++){ if(judge(A.substr(left,step))){ maxLen = max(maxLen,step); if(left>0) left-=2; else left--; step+=2; } } step = 3; for(int left=0; left+step<=n; left++){ if(judge(A.substr(left,step))){ maxLen = max(maxLen,step); if(left>0) left-=2; else left--; step+=2; } } return maxLen; } bool judge(string A){ int left = 0, right = A.size()-1; while(left<right){ if(A[left++]!=A[right--]) return false; } return true; } };