动态规划之回文子串数
来源:互联网 发布: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
阅读全文
0 0
- 动态规划之回文子串数
- 动态规划之回文字符串
- 动态规划之最长回文子序列
- 动态规划之回文最小分割数
- 动态规划回文问题
- 【动态规划】 回文词
- 最长回文:动态规划
- 动态规划解回文
- 回文字符串-动态规划
- 回文串-动态规划
- 算法导论 动态规划之最长回文子序列
- 动态规划 之 回文序列的最小划分
- 动态规划算法之寻找最长回文数串
- 回文数问题;动态规划;
- 【动态规划】37回文字符串
- 动态规划:最长回文字符串
- Vijos1327回文词【动态规划】
- POJ-1159-Palindrome-回文-动态规划
- java-web三大组件(Servlet/Filter/Listener)
- cookie 和session 的区别
- redis数据库在windows下的安装,配置与使用
- angular路由(简单)
- Spring Boot MongoDB How to remove _class from spring data mongodb collection
- 动态规划之回文子串数
- 9. Palindrome Number
- springmvc定时任务同时启动多个线程
- LeetCode671. Second Minimum Node In a Binary Tree
- 【BZOJ 2152 聪聪可可】【点分治 + 一个套路】
- 再接着介绍一下Python呗(12/11)
- 例题9-1 城市里的间谍(A Spy in the Metro, ACM/ICPC World Finals 2003, UVa1025)
- Arrays类的使用
- 信号与槽精讲