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:
- The input string length won't exceed 1000.
回文子串。题意跟第五题非常像,如果没做过第五题建议先做一下第五题。第五题问的是一个字符串里面最长的回文子串是什么,这道题问的是有多少个回文子串。其他做法跟第五题没有任何区别,甚至这道题也有两种做法,但是注意一个细节,每一个字母可以自成一个回文串。其他关于思路的解释请参见第五题的题解。
动态规划
时间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 }
相关题目