码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 647. Palindromic Substrings

时间:2018-02-10 17:02:42      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:string   post   body   length   private   dex   blog   count   markdown   

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.

分析

dp[i][j] 如果等于1就表示 string s 从下标i到j的那部分是 palindromic 的,而 string s 从 m 到 n 的部分只需要满足 s[m]==s[n] 并且 dp[m+1][n-1]==1 (即首尾相等,并且中间的是 palindromic )就是palindromic.

class Solution{
private:
    int dp[1000][1000];
public:
    int countSubstrings(string s) {
        for(int i=0;i<s.size();i++)
            dp[i][i]=1;
        int cnt=s.size();
        for(int len=2;len<=s.size();len++)
            for(int i=0;i<=s.size()-len;i++)
                if(len==2&&s[i]==s[i+1]){
                    dp[i][i+1]=1;
                    cnt++;
                }else if(s[i]==s[i+len-1]&&dp[i+1][i+len-2]==1){
                    dp[i][i+len-1]=1;
                    cnt++;
                }
        return cnt;
    }   
};

LeetCode 647. Palindromic Substrings

标签:string   post   body   length   private   dex   blog   count   markdown   

原文地址:https://www.cnblogs.com/A-Little-Nut/p/8439012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!