Skip to content

Latest commit

 

History

History
88 lines (80 loc) · 1.39 KB

647.回文子串.md

File metadata and controls

88 lines (80 loc) · 1.39 KB

647.回文子串

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

示例 1:

输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"

示例 2:

输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"

  提示:

  • 输入的字符串长度不会超过 1000 。

解法

1、dp

func countSubstrings(s string) int {
	if len(s) <= 1 {
		return len(s)
	}
	dp := make([][]bool, len(s))
	for i := range dp {
		dp[i] = make([]bool, len(s))
	}
	var cnt int
	for i := len(s)-1; i >= 0; i-- {
		for j := i; j < len(s); j++ {
			if i == j {
				dp[i][j] = true
				cnt++
				continue
			}
			if s[i] == s[j] && (i == j-1 || dp[i+1][j-1]) {
				dp[i][j] = true
				cnt++
			}
		}
	}
	return cnt

2、中心拓展

func countSubstrings(s string) int {
	if len(s) <= 1 {
		return len(s)
	}
	var cnt int
	for i := range s {
		cnt++
		var l,r = i-1,i+1
		// 以i为中心向外拓展一次
		for l >= 0 && r < len(s) {
			if s[l] == s[r] {
				cnt++
				l--
				r++
			} else {
				break
			}
		}
		// 以i-1,i为偶数中心向外找一次
		l,r = i-1,i
		for l >= 0 && r < len(s) {
			if s[l] == s[r] {
				cnt++
				l--
				r++
			} else {
				break
			}
		}
	}
	return cnt
}