力扣5. 最长回文子串

Problem: 5. 最长回文子串

题目描述

在这里插入图片描述

思路

1.我们利用双指针中间向两边扩散来判断是否为回文串,则关键是找到以s[i]为中心的回文串;
2.我们编写一个函数string palindrome(string &s, int left, int right)用于返回以索引为i作为中心向两边的的回文子串
3.由于可能出现
奇数或者偶数长度的回文串
,所以我们需要在遍历时,求出**palindrome(s, i, i)palindrome(s, i, i + 1)**的回文串,并取出其中的较大值

复杂度

时间复杂度:

O ( N 2 ) O(N^2) O(N2);其中 N N N为字符串的长度

空间复杂度:

O ( N ) O(N) O(N)

Code

class Solution {
    /**
     * Longest Palindromic Substring
     *
     * @param s Given string
     * @return String
     */
    public String longestPalindrome(String s) {
        String res = "";
        for (int i = 0; i < s.length(); ++i) {
            // The longest callback substring centered on s[i]
            String s1 = palindrome(s, i, i);
            // Longest callback substring centered on s[i] and s[i+1]
            String s2 = palindrome(s, i, i + 1);
            // res = longest(res, s1, s2)
            res = res.length() > s1.length() ? res : s1;
            res = res.length() > s2.length() ? res : s2;
        }
        return res;
    }

    /**
     * Gets the longest palindrome string between [left,right]
     *
     * @param s     Given string
     * @param left  Left pointer
     * @param right Right pointer
     * @return string
     */
    private String palindrome(String s, int left, int right) {
        // Prevent index overreach
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            // Double Pointers, spread out to both sides
            left--;
            right++;
        }
        // Returns the longest palindrome string centered on s[l] and s[r]
        return s.substring(left + 1, right);
    }
}
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值