当前位置:网站首页>leetcode 647. 回文子串
leetcode 647. 回文子串
2022-06-12 17:51:00 【zhuxiaohai68】
给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。
回文字符串 是正着读和倒过来读一样的字符串。
子字符串 是字符串中的由连续字符组成的一个序列。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:s = “abc”
输出:3
解释:三个回文子串: “a”, “b”, “c”
示例 2:
输入:s = “aaa”
输出:6
解释:6个回文子串: “a”, “a”, “a”, “aa”, “aa”, “aaa”
状态:dp[i][j] 表示字符串s在[i,j]区间的子串是否是一个回文串。
状态转移方程:当 s[i] == s[j] && (j - i < 2 || dp[i + 1][j - 1]) 时,dp[i][j]=true,否则为false
这个状态转移方程是什么意思呢?
当只有一个字符时,比如 a ,s[i] == s[j] && (j - i < 2)自然成立,自然是一个回文串。
当有两个字符时,(j - i < 2)是自然成立的,如果是相等的(s[i] == s[j]),比如 aa,也是一个回文串。
当有三个及以上字符时,比如 ababa 这个字符记作串 1,把两边的 a 去掉,也就是 bab 记作串 2,可以看出只要串2是一个回文串,那么左右各多了一个 a 的串 1 必定也是回文串。所以当 s[i]==s[j] 时,自然要看 dp[i+1][j-1] 是不是一个回文串
class Solution(object):
def countSubstrings(self, s):
""" :type s: str :rtype: int """
tot = 0
n = len(s)
dp = [[False]*n for i in range(n)]
for i in range(n-1, -1, -1):
for j in range(i, n):
if i == j:
dp[i][j] = True
tot += 1
elif (s[i] == s[j]) and (j - i == 1):
dp[i][j] = True
tot += 1
elif (s[i] == s[j]) and (dp[i+1][j-1]):
dp[i][j] = True
tot += 1
return tot
边栏推荐
- 小程序和App同时拥有?两者兼得的一种技术方案
- 消息队列存储消息数据的 MySQL 表格
- SQL游标(cursor)详细说明及内部循环使用示例
- 论文《Deep Interest Evolution Network for Click-Through Rate Prediction》
- 迄今微软不同时期发布的SQL Server各版本之间的大致区别,供参考查阅
- Arm64栈回溯
- 进阶之大山-asp.net core 路由程序基础使用演示0.1
- 用好IDE,研发效能提速100%
- String s = null ; String s = new String();String s =““ ;String s ;有什么区别?
- Implementation of asynchronous query of Flink dimension table and troubleshooting
猜你喜欢

App中快速复用微信登录授权的一种方法

C operation database added business data value content case school table

Advanced mountain -asp Net core router basic use demo 0.1

Evolution and thinking of Taobao native R & D mode | DX R & D mode

Arm64 Stack backtrack

小程序和App同时拥有?两者兼得的一种技术方案

Byte flybook Human Resources Kit three sides

Unprecedented analysis of Milvus source code architecture

Tcp/ip family structure and protocol of tcp/ip series overview

vant3+ts DropdownMenu 下拉菜单,数据多能滚动加载
随机推荐
Soringboot下RestTemplateConfig 配置打印请求响应日志
idea 常用快捷键
Application case of smart micro 32-bit MCU for server application cooling control
使用MongoDB官方go库操作MongoDB原创
内核中断整体流程图
The server time zone value ‘�й���ʱ��‘ is unrecognized or represents more than one time zone. ......
406. reconstruct the queue based on height
消息队列存储消息数据的 MySQL 表格
一物一码追踪溯源系统介绍
Vant3+ts dropdownmenu drop-down menu, multi data can be scrolled
Queue priority of message queue practice
Figma from getting started to giving up
徽商期货开户可靠吗?资金安全吗?
I heard that distributed IDS cannot be incremented globally?
Continued 2 asp Net core router basic use demonstration 0.2 acquisition of default controller data
Tutoriel de démarrage rapide JDBC
迄今微软不同时期发布的SQL Server各版本之间的大致区别,供参考查阅
Extreme Programming -- Practice of root cause analysis
Channel Original
TensorFlow2训练数据集的两种方式