[LeetCode] 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.

Thought process:
Dynamic programming. Use a matrix to check if s[i,j] is a palindrome. If so, add one to count.
  1. Sub-problem: check if a sub-string of s is a palindrome.
  2. Function: 
    1. If s[i] == s[j]:
      1. If j - i < 2 (one character or two characters), f[i][j] = true.
      2. Otherwise, f[i][j] = f[i + 1][j - 1].
    2. Otherwise, f[i][j] = false.
  3. Initialization: none.
  4. Answer: f[0][n - 1] will say if s is a palindrome. We want the count of palindromes as we do the DP.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int countSubstrings(String s) {
        int count = 0;
        int len = s.length();
        boolean[][] f = new boolean[len][len];
        
        for (int i = len - 1; i >= 0; i--) {
            for (int j = i; j < len; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    f[i][j] = j - i < 2 ? true : f[i + 1][j - 1];
                    if (f[i][j] == true) {
                        count++;
                    }
                }
            }
        }
        return count;
    }
}

Time complexity: O(n^2).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[HackerRank] Roads and Libraries

[LeetCode] 631. Design Excel Sum Formula