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.
题目链接:https://leetcode.com/problems/palindromic-substrings/
题目分析:子串不是子序列,暴力即可
class Solution {
public int countSubstrings(String s) {
int len = s.length(), ans = 0;
boolean[][] dp = new boolean[len + 2][len + 2];
for (int j = 1; j <= len; j++) {
for (int i = j; i > 0; i--) {
if (s.charAt(i - 1) == s.charAt(j - 1)) {
if (j - i <= 1 || dp[i + 1][j - 1]) {
dp[i][j] = true;;
ans++;
}
}
}
}
return ans;
}
}