第十四周LeetCode
2017-12-06 23:04
120 查看
题目
Palindromic Substrings
难度 Medium
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]代表从第i个位置起到第j个位置的字符串是否为回文(即true还是false),那么dp[i][j]就取决于dp[i+1][j-1]的值以及s[i]是否等于s[j]。当i和j中间没有字符串时(此时i+1>j-1),若s[i]==s[j],那么d[i][j]仍然为true。
因此动态转移方程为 d[i][j]=(s[i]==s[j])&&(dp[i+1][j-1]||(i+1>j-1));
实现代码
Palindromic Substrings
难度 Medium
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]代表从第i个位置起到第j个位置的字符串是否为回文(即true还是false),那么dp[i][j]就取决于dp[i+1][j-1]的值以及s[i]是否等于s[j]。当i和j中间没有字符串时(此时i+1>j-1),若s[i]==s[j],那么d[i][j]仍然为true。
因此动态转移方程为 d[i][j]=(s[i]==s[j])&&(dp[i+1][j-1]||(i+1>j-1));
实现代码
int countSubstrings(string s) { int n = s.size(); int count = 0; vector<vector<int>> dp(n,vector<int>(n)); for (int j = 0; j < n; j++) { dp[j][j] = 1; count++; for (int i = 0; i < j; i++) { if (s[i]==s[j]&&(j-1<=i+1||dp[i+1][j-1])) { dp[i][j]=1; count++; } } } return count; }
相关文章推荐
- Leetcode 算法习题 第十四周
- leetcode第十四周解题总结--二分查找
- 第十四周LeetCode
- 第十四周LeetCode
- leetcode【第十四周】从排序列表中移除重复元素Ⅱ
- 第十四周:[LeetCode]10. Regular Expression Matching
- Leetcode 算法习题 第十四周
- 第十四周LeetCode
- 第十四周leetcode题
- Leetcode 46.Permutations(第十四周作业)
- Leetcode 算法习题 第十四周
- LeetCode题解 第十四周
- leetcode-第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法设计 第十四周
- Leetcode 算法设计 第十四周
- 第十四周:[leetCode] 120. Triangle
- leetcode-python 第十四周
- Leetcode 算法设计 第十四周