当前位置:网站首页>0动态规划中等 LeetCode467. 环绕字符串中唯一的子字符串
0动态规划中等 LeetCode467. 环绕字符串中唯一的子字符串
2022-07-27 04:18:00 【18阿鲁】
分析
计算出分别以26个字母为结尾的最长子字符串的长度,加起来就是所有能够在那个无限循环的数组的找到的子字符串的个数。
所有的子串都是以这26个字母为结尾的。分别求出以26个字母为结尾的最长子字符串,就能得到全部的子字符串。
负雪明烛的题解:
本地的思想其实是「滑动窗口」和「动态规划」相结合。
子串相关的动态规划,一般状态的定义都是「以位置 ii 作为结尾的、符合要求的子串长度」。
这样定义,主要是为了简化,因为知道了 dp[i]dp[i]以后,很容易就能得到 dp[i + 1]dp[i+1]。
比如对于本题,我们把状态定义为「pp 中,以位置 ii 作为结尾的、在 ss 中存在的最长子串长度」。
那么在已知了 dp[i]dp[i] 以后,得到 dp[i + 1]dp[i+1] 时,无非两种情况:
当在 ss中, p[i + 1]p[i+1] 是 p[i]p[i] 的下一个字符,那么说明能 连接上,于是 dp[i + 1] = dp[i] + 1dp[i+1]=dp[i]+1。
当在 ss中, p[i + 1]p[i+1] 不是 p[i]p[i] 的下一个字符,那么说明能 连接不上,于是 dp[i + 1] = 1dp[i+1]=1。
作者:fuxuemingzhu
链接:https://leetcode.cn/problems/unique-substrings-in-wraparound-string/solution/by-fuxuemingzhu-ixas/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public int findSubstringInWraproundString(String p) {
char[] arr = p.toCharArray();
int[] dp = new int[26];
int len = 1;
dp[arr[0]-'a'] = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] - arr[i-1] == 1 || arr[i] == 'a' && arr[i-1] == 'z') {
len++;
} else {
len = 1;
}
if (len > dp[arr[i]-'a']) {
dp[arr[i]-'a'] = len;
}
}
int ans = 0;
for (int num : dp) {
ans += num;
}
return ans;
}
}
边栏推荐
- pinia的持久化存储,pinia使用插件进行持久化存储。
- Eureka service registry
- People don't talk much, engineers don't talk much
- IIC 通信协议 (一)
- JS three methods of traversing arrays: map, foreach, filter
- Echart柱状图中数据显示在图上方
- Post analysis of Data Analyst
- sed输出指定行
- Scala immutable map, variable map, map conversion to other data types
- 结构型模式-适配器模式
猜你喜欢

【C语言】递归详解汉诺塔问题
![[small sample segmentation] msanet: multi similarity and attention guidance for boosting few shot segmentation](/img/b9/270e0f20586a953e83a18f7fac155f.png)
[small sample segmentation] msanet: multi similarity and attention guidance for boosting few shot segmentation

详解左值、右值、左值引用以及右值引用

Shel automatically sets directory permissions

人很话不多,工程师不耍嘴皮子

BSN IPFs (interstellar file system) private network introduction, functions, architecture and characteristics, access instructions

Chapter 6: cloud database

Convolution neural network -- a detailed introduction to convolution of 24 bit color images

【day02】数据类型转换、运算符、方法入门

IIC 通信协议 (一)
随机推荐
playwright网络爬虫实战案例分享
State Hook
Hash table questions (Part 2)
sram、dram、sdram、ddr的区别和用途
Some common instructions in JVM tuning
Do you know about wechat merchant billing?
Chapter 6: cloud database
数据库泰斗王珊:努力创新,精心打磨优质的数据库产品
5.component动态组件的展示
P1438 boring sequence line segment tree + difference
第二轮Okaleido Tiger即将登录Binance NFT,或持续创造销售神绩
Sed output specified line
佳明手表怎么设置用户定制显示
Elastic certification test: 30 day FastPass Study Guide
BigDecimal pit summary & Best Practices
The difference between ArrayList and LinkedList
RSA 非对称 加密解密 加签验签工具
HEAD detached from origin/...导致push失败
微信小程序轮播图
Head detached from origin/... Causes push failure