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".
 1 class Solution {
 2     public int countSubstrings(String s) {
 3         int n = s.length();
 4         int res = 0;
 5         boolean[][] dp = new boolean[n][n];
 6         for (int i = n - 1; i >= 0; i--) {
 7             for (int j = i; j < n; j++) {
 8                 dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
 9                 if(dp[i][j]) ++res;
10             }
11         }
12         return res;
13     }
14 }
15 
16 public class Solution {
17     int count = 0;
18     
19     public int countSubstrings(String s) {
20         if (s == null || s.length() == 0) return 0;
21         
22         for (int i = 0; i < s.length(); i++) { // i is the mid point
23             extendPalindrome(s, i, i); // odd length;
24             extendPalindrome(s, i, i + 1); // even length
25         }
26         return count;
27     }
28     
29     private void extendPalindrome(String s, int left, int right) {
30         while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
31             count++;
32             left--;
33             right++;
34         }
35     }
36 }

 

posted @ 2019-07-05 09:13  北叶青藤  阅读(157)  评论(0编辑  收藏  举报