题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
中心扩展法,以(i, j)为中心,从(i,j)以初始长度等于1和初始长度等于2开始向两边扩展
class Solution { public: pair<int, int> expandAroundCenter(const string& A, int left, int right) { while(left >= 0 && right < A.size() && A[left] == A[right]) { left--; right++; } return {left, right}; } int getLongestPalindrome(string A, int n) { // write code here int left = 0, right = 0; for(int i = 0; i < A.size(); i++) { auto [left1, right1] = expandAroundCenter(A, i, i); // 从子串个度为1开始遍历 auto [left2, right2] = expandAroundCenter(A, i, i + 1); // 从子串长度为2开始遍历 // 更新回文子串的首尾索引,先更新从长度为1开始遍历的,再更新从长度为2开始遍历的 if(right1 - left1 > right - left) { left = left1; right = right1; } if(right2 - left2 > right - left) { left = left2; right = right2; } } return A.substr(left + 1, right - 1 - left).size(); } };