当前位置:网站首页>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
边栏推荐
- JDBC quick start tutorial
- Continued 2 asp Net core router basic use demonstration 0.2 acquisition of default controller data
- Project training of Software College of Shandong University - Innovation Training - network attack and defense shooting range experimental platform of Software College of Shandong University (XXV) - p
- Guitar Pro tutorial how to set up a MIDI keyboard
- 徽商期货公司开户可靠,交易安全吗?
- Error record: illegalstateexception: optional int parameter 'XXXX' is
- 论文《Deep Interest Evolution Network for Click-Through Rate Prediction》
- LCD参数解释及计算
- Tcp/ip family structure and protocol of tcp/ip series overview
- 小程序和App同时拥有?两者兼得的一种技术方案
猜你喜欢

《用户体验要素:以用户为中心的产品设计》笔记

利用小程序快速生成App,只需七步

vant3+ts DropdownMenu 下拉菜单,数据多能滚动加载

1.5 what is an architect (serialization)

MySQL learning notes

一种好用、易上手的小程序IDE

JDBC快速入门教程

PHP implementation of infinite classification tree (recursion and Optimization)

Risc-v ide mounriver studio v1.60 update point introduction
Goframe gredis configuration management | comparison of configuration files and configuration methods
随机推荐
Vant3+ts encapsulates uploader upload image component
qemu+gdb小节
使用MongoDB官方go库操作MongoDB原创
Introduction to cookie usage
Arm64棧回溯
Channel Original
Unprecedented analysis of Milvus source code architecture
vant3+ts+pinia tab选项卡列表页面点击进详情,详情页返回tab高亮在原位置,刷新高亮默认在第一项
vant3+ts DropdownMenu 下拉菜单,数据多能滚动加载
Reconnaître l'originalité de la fonction
Arm64 stack backtracking
数据库SQL操作基础
Use of split method of string
Risc-v ide mounriver studio v1.60 update point introduction
vant3 +ts 封装简易step进步器组件
An easy-to-use IDE for small programs
Vant3 +ts packaged simple step advancer component
利用小程序快速生成App,只需七步
Schedule update | 2022 Microsoft and Intel hacker song competition is in hot registration
进阶之大山-asp.net core 路由程序基础使用演示0.1