[LeetCode] 647. Palindromic Substrings

Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

A substring is a contiguous sequence of characters within the string.

Example 1:

Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

回文子串。

给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。

回文字符串 是正着读和倒过来读一样的字符串。

子字符串 是字符串中的由连续字符组成的一个序列。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindromic-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意跟第五题非常像,如果没做过第五题建议先做一下第五题。第五题问的是一个字符串里面最长的回文子串是什么,这道题问的是回文子串有多少。其他做法跟第五题没有任何区别,甚至这道题也有两种做法,但是注意一个细节,每一个字母可以自成一个回文串。其他关于思路的解释请参见第五题的题解。

动态规划

跟第五题类似,我们还是创建一个二维DP数组,表示 s.subtring(i, j + 1) 形成的子串是否是一个回文。在判断的过程中,如果当前这个子串是一个回文,那么我们就对 count++。最后返回的 count 就是字符串中回文子串的数目

时间O(n^2)

空间O(n^2)

Java实现

 1 class Solution {
 2     public int countSubstrings(String s) {
 3         boolean[][] dp = new boolean[s.length()][s.length()];
 4         int count = 0;
 5         for (int j = 0; j < s.length(); j++) {
 6             for (int i = 0; i <= j; i++) {
 7                 if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1])) {
 8                     dp[i][j] = true;
 9                     count++;
10                 }
11             }
12         }
13         return count;
14     }
15 }

 

中心扩散法

时间O(n^2)

空间O(1)

Java实现

 1 class Solution {
 2     int count = 0;
 3     public int countSubstrings(String s) {
 4         if (s == null || s.length() == 0) {
 5             return 0;
 6         }
 7         for (int i = 0; i < s.length(); i++) { // i is the mid point
 8             extendPalindrome(s, i, i); // odd length;
 9             extendPalindrome(s, i, i + 1); // even length
10         }
11         return count;
12     }
13 
14     private void extendPalindrome(String s, int left, int right) {
15         while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
16             count++;
17             left--;
18             right++;
19         }
20     }
21 }

 

相关题目

5. Longest Palindromic Substring

516. Longest Palindromic Subsequence

647. Palindromic Substrings

LeetCode 题目总结

posted @ 2020-08-19 08:48  CNoodle  阅读(114)  评论(0编辑  收藏  举报