647. Palindromic Substrings

Description

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.

Solution

DP, time O(n^2), space O(n^2)

基础DP题,注意i要从后往前遍历,否则会遇到还没有处理的子问题。

class Solution {
    public int countSubstrings(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        
        int n = s.length();
        boolean[][] isPalindrome = new boolean[n][n];
        int count = 0;
        
        for (int i = n - 1; i >= 0; --i) {  // traverse backward
            for (int j = i; j < n; ++j) {
                isPalindrome[i][j] = s.charAt(i) == s.charAt(j)
                    && (j - i < 2 || isPalindrome[i + 1][j - 1]);
                count += isPalindrome[i][j] ? 1 : 0;
            }
        }
        
        return count;
    }
}

你可能感兴趣的:(647. Palindromic Substrings)