mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0647.回文子串.md
This commit is contained in:
@ -284,6 +284,56 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
> 动态规划:
|
||||
```python
|
||||
class Solution:
|
||||
def countSubstrings(self, s: str) -> int:
|
||||
dp = [[False] * len(s) for _ in range(len(s))]
|
||||
result = 0
|
||||
for i in range(len(s)-1, -1, -1): #注意遍历顺序
|
||||
for j in range(i, len(s)):
|
||||
if s[i] == s[j]:
|
||||
if j - i <= 1: #情况一 和 情况二
|
||||
result += 1
|
||||
dp[i][j] = True
|
||||
elif dp[i+1][j-1]: #情况三
|
||||
result += 1
|
||||
dp[i][j] = True
|
||||
return result
|
||||
```
|
||||
|
||||
> 动态规划:简洁版
|
||||
```python
|
||||
class Solution:
|
||||
def countSubstrings(self, s: str) -> int:
|
||||
dp = [[False] * len(s) for _ in range(len(s))]
|
||||
result = 0
|
||||
for i in range(len(s)-1, -1, -1): #注意遍历顺序
|
||||
for j in range(i, len(s)):
|
||||
if s[i] == s[j] and (j - i <= 1 or dp[i+1][j-1]):
|
||||
result += 1
|
||||
dp[i][j] = True
|
||||
return result
|
||||
```
|
||||
|
||||
> 双指针法:
|
||||
```python
|
||||
class Solution:
|
||||
def countSubstrings(self, s: str) -> int:
|
||||
result = 0
|
||||
for i in range(len(s)):
|
||||
result += self.extend(s, i, i, len(s)) #以i为中心
|
||||
result += self.extend(s, i, i+1, len(s)) #以i和i+1为中心
|
||||
return result
|
||||
|
||||
def extend(self, s, i, j, n):
|
||||
res = 0
|
||||
while i >= 0 and j < n and s[i] == s[j]:
|
||||
i -= 1
|
||||
j += 1
|
||||
res += 1
|
||||
return res
|
||||
```
|
||||
|
||||
Go:
|
||||
```Go
|
||||
|
Reference in New Issue
Block a user