leetcode讲解--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".

Note:

  1. The input string length won't exceed 1000.

题目地址

讲解

题目的意思是:找出字符串中所有回文串,不同位置的回文串不算同一个。这道题我只能想到从左到右按照从1到s.length的长度依次扫N遍。而且这还不包括判断是否是回文串这一步所用的时间。而判断回文串显然是可以有重复计算的子问题的,所以要用到动态规划。

依旧是用规模从大到小的备忘录递归解法。这道题做下来还是挺轻松的,我发现我越来越喜欢用递归了,对递归的掌控力也变强了。

java代码

class Solution {
    private boolean[][] dp;
    public int countSubstrings(String s) {
        int result=0;
        dp = new boolean[s.length()][s.length()];
        for(int i=0;i

你可能感兴趣的:(动态规划,字符串处理,算法,leetcode)