mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -397,6 +397,7 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Go:
|
### Go:
|
||||||
|
> 动态规划:
|
||||||
|
|
||||||
```Go
|
```Go
|
||||||
func countSubstrings(s string) int {
|
func countSubstrings(s string) int {
|
||||||
@ -422,6 +423,47 @@ func countSubstrings(s string) int {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
> 动态规划:简洁版
|
||||||
|
```Go
|
||||||
|
func countSubstrings(s string) int {
|
||||||
|
res := 0
|
||||||
|
dp := make([][]bool, len(s))
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
dp[i] = make([]bool, len(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := len(s) - 1; i >= 0; i-- {
|
||||||
|
for j := i; j < len(s); j++ {
|
||||||
|
if s[i] == s[j] && (j-i <= 1 || dp[i+1][j-1]) {
|
||||||
|
res++
|
||||||
|
dp[i][j] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 双指针法:
|
||||||
|
```Go
|
||||||
|
func countSubstrings(s string) int {
|
||||||
|
extend := func(i, j int) int {
|
||||||
|
res := 0
|
||||||
|
for i >= 0 && j < len(s) && s[i] == s[j] {
|
||||||
|
i --
|
||||||
|
j ++
|
||||||
|
res ++
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
res := 0
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
res += extend(i, i) // 以i为中心
|
||||||
|
res += extend(i, i+1) // 以i和i+1为中心
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Javascript:
|
### Javascript:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user