动态规划之回文子串数

来源:互联网 发布:origin有没有mac版 编辑:程序博客网 时间:2024/05/16 15:54

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

Example 2:

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

Note:

The input string length won't exceed 1000.

分析

判断子串是否存在回文子串,利用动态规划的思想,可以理解成如果收尾字母相同,则它是否是回文子串依赖于次首尾字母是否相同,然后终止条件是首尾位置相差3以内。关键代码:dp[i][j] = (s[i] == s[j] && ((j - i < 3) || dp[i+1][j-1]));总体的思路是以从字符串的从开始到结尾的每一个字符,判断从0到每一个字符之间是不是回文串

总体的复杂度是空间复杂度是O(n2),时间复杂度是O(n2)。

代码

class Solution {public:    int countSubstrings(string s) {        int _size = s.length();        if (!_size) return 0;        vector<vector<bool>> dp(_size, vector<bool>(_size, false));        int count = 0;        for (int j = 0; j < _size; j++) {            for (int i = j; i >= 0; i--) {                dp[i][j] = (s[i] == s[j] && ((j - i < 3) || dp[i+1][j-1]));                if (dp[i][j]) count++;            }        }        return count;    }};

题目地址:LeetCode647

原创粉丝点击