[Leetcode Longest Palindromic Substring 最长回文子串

Palindromic Substrings 回文子串

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

  • Example 1:

Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.

  • Example 2:

Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.

  • Note:

The input string length won’t exceed 1000.

分析题目

求回文子串的数目.基本思路是对于每个子串的中心(可以是一个字符,或者是两个字符的间隙,比如串abc,中心可以是a,b,c,或者是ab的间隙,bc的间隙)往两边同时进行扫描,直到不是回文串为止。假设字符串的长度为n,那么中心的个数为2*n-1(字符作为中心有n个,间隙有n-1个)。对于每个中心往两边扫描的复杂度为O(n),所以时间复杂度为O((2*n-1)*n)=O(n^2),空间复杂度为O(1),代码如下:

代码

Complexity - Time: O(n2), Space: O(1)

class Solution {

    private int count = 0;
    public int countSubstrings(String s) {        
        //corner case
        if(s == null || s.length() == 0){
            return count;
        }

        for(int i = 0; i < s.length(); i++){
            helper(s, i, i);
            helper(s, i, i + 1);
        }
        return count;
    }

    private void helper(String s, int left, int right){        
        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            count++;
            left--;
            right++;
        }
        return;
    }
}

Longest Palindromic Substring 最长回文子串

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

  • Example 1:
    Input: “babad”
    Output: “bab”
  • Note: “aba” is also a valid answer.
  • Example 2:
    Input: “cbbd”
    Output: “bb”

分析题目

本题让我们求最长回文子串,在上题回文串数目的基础上,每次记录回文串的长度,如果大于max ,更新max,循环结束返回最长的子串.
本题用马拉车算法Manacher’s Algorithm,可将时间复杂度提升到了O(n)这种逆天的地步(待整理)

代码

Complexity - Time: O(n2), Space: O(1)

class Solution {
    private int lo, max;
    public String longestPalindrome(String s) {
        if (s.length() < 2) {
            return s;
        }
        for (int i = 0; i < s.length(); ++i) {
            helper(s, i, i);
            helper(s, i, i + 1);
        }
        return s.substring(lo,lo + max); //substring 方法返回不包括end索引处字符.
    }
    private void helper (String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        } 
        if (right - left - 1 > max) {
            lo = left + 1;
            max = right - left - 1;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值