Skip to content

Latest commit

 

History

History
101 lines (88 loc) · 2.44 KB

647. Palindromic Substrings.md

File metadata and controls

101 lines (88 loc) · 2.44 KB

leetcode-cn Daily Challenge on August 19th, 2020.


Difficulty : Medium

Related Topics : StringDynamic Programming


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.

Solution

  • mine
    • Java
      • Runtime: 1 ms, faster than 99.95%, Memory Usage: 37.5 MB, less than 88.33% of Java online submissions
        //O(N^2)time
        //O(N)space
        public int countSubstrings(String s) {
            char[] arr = s.toCharArray();
            int res = 0;
            for(int i = 0; i < arr.length; i++){
                res += check(arr, i, i);
                res += check(arr, i, i + 1);
            }
            return res;
        }
        
        int check(char[] arr, int s, int e){
            int res = 0;
            while(s >= 0 && e < arr.length && arr[s--] == arr[e++]){
                res++;
            }
            return res;
        }
        

  • the most votes
  • Manacher's Algorithm Runtime: 1 ms, faster than 99.95%, Memory Usage: 37.2 MB, less than 97.04% of Java online submissions
    // O(N)time
    // O(N)space
    public int countSubstrings(String S) {
        char[] A = new char[2 * S.length() + 3];
        A[0] = '@';
        A[1] = '#';
        A[A.length - 1] = '$';
        int t = 2;
        for (char c: S.toCharArray()) {
            A[t++] = c;
            A[t++] = '#';
        }
    
        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 ans = 0;
        for (int v: Z) ans += (v + 1) / 2;
        return ans;
    }