算法珠玑——最长回文子串(5)
算法珠玑——最长回文子串(5)
三指针?
/*
* @lc app=leetcode.cn id=5 lang=cpp
*
* [5] 最长回文子串
*/
// @lc code=start
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
// (object) base for end case: start and mxlen
int mxlen = 0, start = 0;
int left, right;
// (base/end)induction step: itertive
for (int i = 0; i < n; ++i)
{
left = i;
right = i;
// sub induction step: shift right
while (right+1 < n && s[right] == s[right+1])
++right;
// sub induction step: adjust left and right
while (left-1 >= 0 && right+1 < n && s[left-1] == s[right+1])
{
--left;
++right;
}
// sub induction step: set start and maxlen
if (mxlen < right-left+1)
{
mxlen = right-left+1;
start = left;
}
}
// end case
return s.substr(start, mxlen);
}
};
// @lc code=end

浙公网安备 33010602011771号