当前位置:网站首页>【剑指Offer】48. 最长不含重复字符的子字符串
【剑指Offer】48. 最长不含重复字符的子字符串
2022-06-27 20:46:00 【LuZhouShiLi】
剑指 Offer 48. 最长不含重复字符的子字符串
题目
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
思路
设状态数组dp,dp[j]代表以字符s[j]为结尾的“最长不重复子字符串”的长度
转移方程:固定右边界j,设字符s[j]左边距离最近的相同字符为s[i],即s[i] = s[j]
当i < 0,即s[j]左边无相同字符,则dp[j] = dp[j - 1] + 1;当dp[j - 1] < j - i, 说明字符s[i]在子字符串dp[j - 1]区间之外,则dp[j] = dp[j - 1] + 1;当dp[j - 1] >= j - i,说明字符s[i]在字符串dp[j - 1]区间之内,则dp[j]的左边界由s[i]决定,即dp[j] = j - i;
返回max(dp)
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> dic = new HashMap<>();// 定义一个哈希表
int res = 0,tmp = 0;
for(int j = 0; j < s.length(); j++)
{
int i = dic.getOrDefault(s.charAt(j),-1);// s.charAt(j)获得的是当前位置的字符,然后从哈希表中查找该字符上一次出现的位置
// 将该字符位置存入哈希表
dic.put(s.charAt(j),j);// 更新哈希表
// 计算当前位置和上一次出现的位置之差 和tmp(tmp是前一个字符的最长子字符串长度)进行比较
// 这里进行更新当前字符的最长子字符串长度
if(tmp < j -i)
{
tmp = tmp + 1;
}
else
{
tmp = j - i;
}
// 更新res
res = Math.max(res,tmp);// max(dp[j - 1],dp[j])
}
return res;
}
}
边栏推荐
- Zabbix6.0升级指南-数据库如何同步升级?
- 因美纳陷数据泄露“丑闻”:我国基因数据安全能交给美企吗?
- Azure Kinect DK 实现三维重建 (PC非实时版)
- [network] common request methods
- [Blue Bridge Cup training 100 questions] scratch digital calculation Blue Bridge Cup competition special prediction programming question collective training simulation exercise question No. 16
- Introduction to MySQL operation (IV) -- data sorting (ascending, descending, and multi field sorting)
- Do you know the full meaning of log4j2 configurations? Take you through all the components of log4j2
- 最新云开发微信余额充电器特效小程序源码
- 网易云“情怀”底牌失守
- 居家办公竟比去公司上班还累?
猜你喜欢

Practice torch FX: pytorch based model optimization quantization artifact

Death of 5 yuan youkuang in Yuanqi forest

Working at home is more tiring than going to work at the company?

电子科大(申恒涛团队)&京东AI(梅涛团队)提出用于视频问答的结构化双流注意网络,性能SOTA!优于基于双视频表示的方法!

Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)

MySQL十八:写语句的执行过程

各种loam总结(激光slam)

打造南沙“强芯”,南沙首届IC Nansha大会召开

Feign通过自定义注解实现路径的转义

雪糕还是雪“高”?
随机推荐
消除el-image图片周围间隙
“顶流爱豆制造机”携手四个产业资本,做LP
6G显卡显存不足出现CUDA Error:out of memory解决办法
居家办公竟比去公司上班还累?
游戏手机平台简单介绍
[electron] basic learning
Azure Kinect DK 实现三维重建 (PC非实时版)
Hiplot 在線繪圖工具的本地運行/開發庫開源
通过 MQTT 检测对象和传输图像
Realization of kaggle cat dog recognition by pytorch
Consumer finance app user insight in the first quarter of 2022 - a total of 44.79 million people
量化交易入门教程
The latest cloud development wechat balance charger special effect applet source code
Web worker introduction and use cases
个人TREE ALV 模版-加快你的开发
Discuz small fish game wind shadow legend business gbk+utf8 version template /dz game website template
移动端避免使用100vh[通俗易懂]
官宣!Apache Doris 从 Apache 孵化器毕业,正式成为 Apache 顶级项目!
实践torch.fx:基于Pytorch的模型优化量化神器
Azure Kinect DK realizes 3D reconstruction (Jetson real-time version)