Skip to content

Commit

Permalink
Update 0647.回文子串.md
Browse files Browse the repository at this point in the history
  • Loading branch information
z80160280 committed Jun 9, 2021
1 parent a4b7399 commit 9b3853e
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions problems/0647.回文子串.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9b3853e

Please sign in to comment.