Question Link

https://leetcode.com/problems/palindromic-substrings/

Question Description

Given a String s, return the number of palindromic substrings in it.
Input: s= abbac

Simulation

Solution 1: Two Pointers

Check every character, and expand them until reach boundary

Leetcode 647 Palindromic Substrings - 图1

Solution 2: Two Pointers + DP

I\J a b b a c
a T F F T F
b F T T F F
b F F T F F
a F F F T F
c F F F F T

DP(i,j) represent if a substring s within the range [i,j] is a palindrome or not.
Case 1: I
If i>j, then DP(i,j) = False. j should always larger than i as this is what we defined in range
If i==j, then DP(i,j) = True. Each single letter is considered as a palindrome
If iif s.charAt(i) !=s.charAt(j), DP(i,j)= False
if s.charAt(i) == s.charAt(j), then DP(i,j)= DP(i+1,j-1) || i+1>=j-1

Traverse Order
Main Diagonal: T T T T T
Sub Diagonal: F T F F
Sub Diagonal: F F F
Sub Diagonal: T F
Sub Diagonal: F

Implementation

Solution 1: Two Pointers

  1. public int countSubstrings(String s) {
  2. var count = 0;
  3. for (var i = 0; i < s.length(); i++)
  4. count += countSubstrings(s, i, i) + countSubstrings(s, i, i + 1);
  5. return count;
  6. }
  7. private int countSubstrings(String s, int start, int end) {
  8. var count = 0;
  9. while (start >= 0 && end < s.length() && s.charAt(start--) == s.charAt(end++))
  10. count++;
  11. return count;
  12. }

Solution 2: DP