题解 | #最长回文子串#

最长回文子串

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();
    }
};
全部评论

相关推荐

01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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