当前位置:网站首页>【剑指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;
}
}
边栏推荐
- [随笔]ME53N 增加按钮,调用URL
- webService
- Discuz taobaoke website template / Dean taobaoke shopping style commercial version template
- Advertising is too "wild", Yoshino "surrenders"
- 本机部署一个MongoDB单节点服务器,并启用auth验证、开启oplog
- Summary of various loams (laser SLAM)
- Spark bug Practice (including bug: classcastexception; connectexception; noclassdeffounderror; runtimeexceptio, etc.)
- Mysql database experiment report (I)
- 雪糕还是雪“高”?
- 跟着存档教程动手学RNAseq分析(一)
猜你喜欢

Mysql database experiment report (I)

Livox lidar+apx15 real-time high-precision radar map reproduction and sorting

Small chip chiplet Technology

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

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

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

雪糕还是雪“高”?

Discuz淘宝客网站模板/迪恩淘宝客购物风格商业版模板

元气森林的5元有矿之死

MapReduce初级编程实践
随机推荐
使用同花顺手机炒股安全吗?
云辅助隐私集合求交(Server-Aided PSI)协议介绍:学习
Classification of cifar-10 dataset with pytorch
小芯片chiplet技术杂谈
实践torch.fx:基于Pytorch的模型优化量化神器
First principles (optimal solution theory)
Working at home is more tiring than going to work at the company?
Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)
打造南沙“强芯”,南沙首届IC Nansha大会召开
PHP connects to database to realize user registration and login function
Personal tree ALV template - accelerate your development
Spark BUG实践(包含的BUG:ClassCastException;ConnectException;NoClassDefFoundError;RuntimeExceptio等。。。。)
移动端避免使用100vh[通俗易懂]
基于 ESXi 的黑群晖 DSM 7.0.1 安装 VMware Tools
Summary of various loams (laser SLAM)
webService
电子科大(申恒涛团队)&京东AI(梅涛团队)提出用于视频问答的结构化双流注意网络,性能SOTA!优于基于双视频表示的方法!
Redis principle - string
Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板
Technical implementation process of easycvr platform routing log function [code attached]