add 647. Palindromic Substrings.md 🍺

This commit is contained in:
ShusenTang 2020-05-05 17:12:10 +08:00
parent c23a27970e
commit d2df3c1007
2 changed files with 70 additions and 0 deletions

View File

@ -325,6 +325,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
| 621 |[Task Scheduler](https://leetcode.com/problems/task-scheduler/)|[C++](solutions/621.%20Task%20Scheduler.md)|Medium| |
| 628 |[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/628.%20Maximum%20Product%20of%20Three%20Numbers.md)|Easy| |
| 643 |[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/643.%20Maximum%20Average%20Subarray%20I.md)|Easy| |
| 647 |[Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)|[C++](solutions/647.%20Palindromic%20Substrings.md)|Medium| |
| 661 |[Image Smoother](https://leetcode.com/problems/image-smoother)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/661.%20Image%20Smoother.md)|Easy| |
| 665 |[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/665.%20Non-decreasing%20Array.md)|Easy| |
| 714 |[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/714.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee.md)|Medium| |

View File

@ -0,0 +1,69 @@
# [647. Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
# 思路
计算有多少个回文子串。
## 思路一、扩散法
根据回文串的定义回文串是对称的。所以我们可以以字符串中的每个字符作为回文串中心位置然后向两边扩散每当成功匹配两个左右两个字符就说明找到了一个回文串res自增1。注意回文字符串有奇数和偶数两种形式处理方式略有不同。
空间复杂度O(1) 时间复杂度O(n^2)
## 思路二、动态规划
还可以用动归来做:
```
dp[i][j] (i <= j) 定义成子字符串s[i,...,j]是否是回文串
```
所以初始状态就是`dp[i][i] = true`,状态转移方程为:
```
if s[i] == s[j] && (i+1 == j || dp[i+1][j-1]) :
dp[i][j] = true
```
空间复杂度O(n^2) 时间复杂度O(n^2),亲测比思路一慢不少
# C++
## 思路一
``` C++
class Solution {
public:
int countSubstrings(string s) {
int n = s.size(), res = 0;
for(int i = 0; i < n; i++){
// 奇
for(int j = 0; j <= min(i, n - 1 - i); j++){
if(s[i-j] == s[i+j]) res++;
else break;
}
// 偶
for(int j = 1; j <= min(i+1, n - 1 - i); j++){
if(s[i-j+1] == s[i+j]) res++;
else break;
}
}
return res;
}
};
```
## 思路二
``` C++
class Solution {
public:
int countSubstrings(string s) {
int n = s.size(), res = 0;
vector<vector<bool>>dp(n, vector<bool>(n, false));
for(int i = n - 1; i >= 0; i--)
for(int j = n - 1; j >= i; j--){
if(s[i] == s[j] && (i == j || i+1 == j || dp[i+1][j-1])){
dp[i][j] = true;
res++;
}
}
return res;
}
};
```