Add solution 647

This commit is contained in:
YDZ
2021-03-28 12:01:36 +08:00
parent 427b25d4b7
commit b4d7a80343
27 changed files with 613 additions and 391 deletions

View File

@ -0,0 +1,23 @@
package leetcode
func countSubstrings(s string) int {
res := 0
for i := 0; i < len(s); i++ {
res += countPalindrome(s, i, i)
res += countPalindrome(s, i, i+1)
}
return res
}
func countPalindrome(s string, left, right int) int {
res := 0
for left >= 0 && right < len(s) {
if s[left] != s[right] {
break
}
left--
right++
res++
}
return res
}

View File

@ -0,0 +1,47 @@
package leetcode
import (
"fmt"
"testing"
)
type question647 struct {
para647
ans647
}
// para 是参数
// one 代表第一个参数
type para647 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans647 struct {
one int
}
func Test_Problem647(t *testing.T) {
qs := []question647{
{
para647{"abc"},
ans647{3},
},
{
para647{"aaa"},
ans647{6},
},
}
fmt.Printf("------------------------Leetcode Problem 647------------------------\n")
for _, q := range qs {
_, p := q.ans647, q.para647
fmt.Printf("【input】:%v 【output】:%v\n", p, countSubstrings(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,64 @@
# [647. Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
## 题目
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:**
1. The input string length won't exceed 1000.
## 题目大意
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
## 解题思路
- 暴力解法,从左往右扫一遍字符串,以每个字符做轴,用中心扩散法,依次遍历计数回文子串。
## 代码
```go
package leetcode
func countSubstrings(s string) int {
res := 0
for i := 0; i < len(s); i++ {
res += countPalindrome(s, i, i)
res += countPalindrome(s, i, i+1)
}
return res
}
func countPalindrome(s string, left, right int) int {
res := 0
for left >= 0 && right < len(s) {
if s[left] != s[right] {
break
}
left--
right++
res++
}
return res
}
```