[Leetcode Longest Palindromic Substring 最长回文子串

版权声明:作者:Britesun 欢迎转载,与人分享是进步的源泉! https://blog.csdn.net/qq_34807908/article/details/82019071

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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34807908/article/details/82019071