题解 | #最长回文子串#

最长回文子串

http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af

class Solution {
public:
    int getLongestPalindrome(string A, int n) {
        // write code here
        if(n < 2)return A.size();
        //处理特殊情况
        int max = 0;
        for(int i = 0; i < n;){
            if(n-i <= max / 2) break;//剩余数量不足最大值的一半时,直接终止
            int l = i;
            int r = i;
            while(r < n-1 && A[r+1] == A[r]) r++;//去除重复的中心字符,如bbb
            i = r + 1;
            while(r < n- 1 && l > 0 && A[r+1] == A[l-1]){
                r++;
                l--;
            }
            max = (r-l+1)>max?r-l+1:max;
        }
        return max;
    }
};
全部评论
最长文字串
点赞 回复 分享
发布于 2022-10-21 20:30 陕西

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务