动态规划-647. Palindromic Substrings

来源:互联网 发布:硬盘分区丢失数据恢复 编辑:程序博客网 时间:2024/05/16 12:44

题目:

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: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

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

Note:

题意解读:给定一个字符串,统计字符串中回文串的个数。注意不同开始和结束的子串即使他们包括相同的字符,也算作不同子串

//思路 ①判断一遍是否是回文串,如果对应子串是回文串,则置1,否则置0//    ②累加dp矩阵// dp[i][j]表示对应子串是否是回文串//状态转移方程 dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1])class Solution {    public int countSubstrings(String s) {        int n = s.length();        boolean[][] dp = new boolean[n][n];        int count = 0;        //倒序遍历        // for(int i = n-1; i >= 0; i--){        //     for(int j = i ; j < n; j++){        //        dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);         //        if(dp[i][j])        //            count++;        //     }        // }        //正序遍历        for(int j = 0; j < n; j++){            for(int i = 0 ; i <= j; i++){               dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);                if(dp[i][j])                   count++;            }        }        return count;    }}


原创粉丝点击