647. Palindromic Substrings (DP)
来源:互联网 发布:淘宝网店上货教程 编辑:程序博客网 时间:2024/04/30 02:44
1.Description
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.
2. Analysis
分析并不难,采用自底向上的方法,从简单到复杂,从小规模到大规模。假如输入的string长度为1,那么显然result=1,假如为2,那么result可能为2也可能为3。假如为3,那么result可能为3,4,6。举例:“aba”为4,“abc”为3,“aaa”为6。(注意没有5,为什么)。我们假设
所以状态转移方程可用下列表示:
3. Code
class Solution {public: static int recur(string& str, int e) { int ret = 0; for(int i = e; i >= 0; i--) { int count = 0;//成对的数是否满足回文 //分奇偶 if((e-i)%2==0) { int mid = (e+i)/2; for(int j = 0; mid-j >= 0 && mid + j <= e && str[mid-j] == str[mid + j]; j++) { count++; } } else { for(int j = i, k = e; j < k && str[j] == str[k]; j++, k--) { count++; } } if(count == (e-i)/2 + 1) //满足回文,ret加1 ret++; } return ret; } int countSubstrings(string s) { int n = s.length(); int res[n+1] = {0}; for(int i = 1; i <= n; i++) { res[i] = recur(s, i-1) + res[i-1]; } return res[n]; }};
- 647. Palindromic Substrings (DP)
- 647. Palindromic Substrings
- 647. Palindromic Substrings
- [leetcode]647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode]647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode] 647. Palindromic Substrings
- 647. Palindromic Substrings
- 【LeetCode】647. Palindromic Substrings
- 647. Palindromic Substrings
- 647. Palindromic Substrings
- Leetcode 647. Palindromic Substrings
- 647. Palindromic Substrings
- LeetCode:647. Palindromic Substrings
- #leetcode#647. Palindromic Substrings
- 647. Palindromic Substrings
- 647. Palindromic Substrings
- 在线判题(字符串)
- spring来进行正式、测试环境无缝式切换
- 如何搭建一个独立博客——简明Github Pages与Hexo教程
- cut命令
- Codeforces 879C Short Program【思维】
- 647. Palindromic Substrings (DP)
- @Transactional(rollbackFor=Exception.class)的使用
- Error parsing HTTP request header
- 杨晖菱形
- UVALive 7267 Mysterious Antiques in Sackler Museum(dfs)
- java操作BerkeleyDB数据库判断元素是否存在(过滤器)
- CodeForces
- Android 软键盘遮挡Dialog
- 讲讲排序(C++描述 )