友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

647. 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:

  1. The input string length won’t exceed 1000.

解题思路

马拉车算法

思考题

学习马拉车算法。

参考资料

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:

  1. The input string length won’t exceed 1000.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
 * Runtime: 1 ms, faster than 100.00% of Java online submissions for Palindromic Substrings.
 * Memory Usage: 37.8 MB, less than 11.39% of Java online submissions for Palindromic Substrings.
 *
 * Copy from: https://leetcode-cn.com/problems/palindromic-substrings/solution/hui-wen-zi-chuan-by-leetcode/[回文子串 - 回文子串 - 力扣(LeetCode)]
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2020-01-31 23:17
 */
public int countSubstrings(String s) {
    char[] A = new char[2 * s.length() + 3];
    A[0] = '@';
    A[1] = '#';
    A[A.length - 1] = '$';
    int j = 2;
    for (char c : s.toCharArray()) {
        A[j++] = c;
        A[j++] = '#';
    }

    int[] Z = new int[A.length];
    int center = 0, right = 0;
    for (int i = 1; i < Z.length - 1; i++) {
        if (i < right) {
            Z[i] = Math.min(right - i, Z[2 * center - i]);
        }
        while (A[i + Z[i] + 1] == A[i - Z[i] - 1]) {
            Z[i]++;
        }
        if (i + Z[i] > right) {
            center = i;
            right = i + Z[i];
        }
    }
    int result = 0;
    for (int i : Z) {
        result += (i + 1) / 2;
    }
    return result;
}