"Palindrome Substring" of LeetCode Series

647. Kaibunko skewers

Given a string, return how many palindrome substrings in this string.

Two identical palindrome substrings appear in different positions and are considered to be two palindrome strings.

a, aa, aaa, aba, aabaa, abcba are all considered to be palindrome substrings.

Example 1 :

enter

"aaa"

Output

6

Description

a、a、a、aa、aa、aaa

Example 2 :

enter

"abcb"

Output

5

Description

a、b、c、b、bcb

Function signature :

import java.util.*;

public class Solution{
    
    
  	public int palindromeCount(String str){
    
    
      	
    }
}

Note that the title says 回文子串, not 回文子序列, that substrings are continuous, and subsequences are not required to be continuous.

Method 1: Center expansion

The simplest way to calculate how many palindrome substrings there are is to enumerate all palindrome substrings, and there are two ways of enumerating all palindrome substrings, namely:

  • Enumerate all the substrings, and then determine whether these substrings are palindrome;
  • Enumerate every possible palindrome center, and then use two pointers to expand to the left and right sides respectively. When the two pointers point to the same element, expand, otherwise stop expanding.

Suppose the length of the string is n. We can see that the former will use O (n 2) O(n^2)O ( n2 )Time to enumerate all substrings [li ⋅ ⋅ ri] s[l_{i}···r_{i}]s[liri] , Reused afterwardsO (ri − li + 1) O (r_i --l_i + 1)O ( rili+1 ) The time to detect whether the current substring is a palindrome, the time complexity of the entire algorithm isO (n 3) O(n^3)O ( n3 ). The latter enumerates the center of the palindrome isO (n) O(n)O ( n ) , the number of expansions for each palindrome center is alsoO (n) O(n)O ( n ) , so the time complexity isO (n 2) O(n^2)O ( n2 ). So we choose the second method to enumerate all palindrome substrings.

In the implementation, we need to deal with a problem, that is, how to enumerate all possible palindrome centers in an orderly manner. We need to consider the two cases of palindrome length 奇数and palindrome length 偶数. If the length of the palindrome is odd, then the center of the palindrome is one character; if the length of the palindrome is even, then the center is two characters. Of course you can do two loops to enumerate the palindrome of odd length and even length respectively, but we can also do it with one loop. We might as well write a set of observations, assuming n = 4, we can list the possible palindrome centers:

Number iii Palindrome center left starting position li l_ili Right starting position of palindrome center ri r_iri
0 0 0
1 0 1
2 1 1
3 1 2
4 2 2
5 2 3
6 3 3

As shown in the figure below :

From this we can see that a string of length nn will generate 2n-12n−1 groups of palindrome centers [li, ri] [l_i, r_i][li,ri],其中 l i = i 2 l_i = \frac{i}{2} li=2i r i = l i + ( i % 2 ) r_i = l_i + (i \%2) ri=li+( i % 2 ) . So we only need to start from0 00 to2 n − 1 2n−12 n 1 Traverse $i$ to get all possible palindrome centers, thus unifying the two cases of odd length and even length.

The Java implementation is as follows :

class Solution {
    
    
    public int countSubstrings(String s) {
    
    
        int res = 0;
        int len = s.length();
        for(int i = 0; i <= 2*len-1; i++){
    
    
            int left = i/2;
            int right = i/2 + i%2;
            while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)){
    
    
                left--;
                right++;
                res++;
            }
        }
        return res;
    }
}
  • Time complexity: O (n 2) O(n^2)O ( n2)
  • Space complexity: O (1) O(1)O ( 1 )

The input and output should also be considered for the written test:

The complete code is as follows:

import java.util.Scanner;

/**
 * @Author Hory
 * @Date 2020/10/22
 */
public class Palindrome {
    
    
  
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        int out = countSubstrings(str);
        System.out.println(out);
    }

    public static int countSubstrings(String s) {
    
    
        int res = 0;
        int len = s.length();
        for(int i = 0; i <= 2*len-1; i++){
    
    
            int left = i/2;
            int right = i/2 + i%2;
            while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)){
    
    
                left--;
                right++;
                res++;
            }
        }
        return res;
    }
}

Method 2: Manacher algorithm

The Manacher algorithm, also known as the "horse-drawn cart" algorithm, can solve a string problem with a time complexity of O(n) 最长回文子串长度.

For Manacher's solution, please refer to Leetcode's official problem solution.

Guess you like

Origin blog.csdn.net/weixin_44471490/article/details/109250417