5. 最长回文子串

题目

代码

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.size()==1)
          return s;
        string max=s.substr(0,1);
        int maxLength=0;
        for(int i=0;i<s.size();i++)
        {
          
            int step=0;
            //偶数对称型
            while((i+step+1)<s.size()&&(i-step)>=0&&s[i+step+1]==s[i-step])
              step++;
            if(step>0&&(2*step)>maxLength)
            {
                maxLength=2*step;
                max=s.substr(i-step+1,step*2);
            }
            //奇数对称型
            step=1;
            while((i-step)>=0&&(i+step)<s.size()&&s[i-step]==s[i+step])
              step++;
            if(step>1&&(2*step-1)>maxLength)
            {
               maxLength=2*step-1;
               max=s.substr(i-step+1,step*2-1);
            }
          
        }
      return max;
    }
};
https://github.com/li-zheng-hao
原文地址:https://www.cnblogs.com/lizhenghao126/p/11053605.html