当前位置:网站首页>【剑指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;
}
}
边栏推荐
- PE buys a underwear company
- 【经典干货书】数据科学中的信息理论方法,561页pdf
- [Blue Bridge Cup training 100 questions] scratch digital calculation Blue Bridge Cup competition special prediction programming question collective training simulation exercise question No. 16
- 最虚的华人首富更虚了
- Gartner focuses on low code development in China how UNIPRO practices "differentiation"
- Livox lidar+apx15 real-time high-precision radar map reproduction and sorting
- Classification of cifar-10 dataset with pytorch
- Brief introduction to game phone platform
- 打造南沙“强芯”,南沙首届IC Nansha大会召开
- [can you really use es] Introduction to es Basics (II)
猜你喜欢

To build a "strong core" in Nansha, the first IC Nansha conference was held in Nansha

官宣!Apache Doris 从 Apache 孵化器毕业,正式成为 Apache 顶级项目!

STM32与RC522简单公交卡系统的设计

广告太「野」,吉野家「渡劫」

netERR_ CONNECTION_ Refused solution

通过 MQTT 检测对象和传输图像

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

【经典干货书】数据科学中的信息理论方法,561页pdf

Summary of solutions to cross system data consistency problems

webService
随机推荐
[suggested collection] ABAP essays-excel-4-batch import recommended
Do you know the full meaning of log4j2 configurations? Take you through all the components of log4j2
What problems should be paid attention to in the serpentine wiring of PCB?
This kind of people began to be robbed by VC with a monthly salary of 80000 yuan
这届考生,报志愿比高考更“拼命”
个人TREE ALV 模版-加快你的开发
新加坡国立大学|采用无模型强化学习方法评估能源效益数据中心的节能情况
Sentinel
凌云出海记 | 沐融科技&华为云:打造非洲金融SaaS解决方案样板
MySQL删除表后如何使ID从1开始
跟着存档教程动手学RNAseq分析(二)
netERR_ CONNECTION_ Refused solution
通过tidymodels使用XGBOOST
Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板
Zabbix6.0升级指南-数据库如何同步升级?
6G显卡显存不足出现CUDA Error:out of memory解决办法
月薪3万的狗德培训,是不是一门好生意?
The National University of Singapore 𞓜 uses model free reinforcement learning to evaluate the energy efficiency of the energy efficiency data center
OData - API using SAP API hub in SAP S4 op
Stream + Nacos