剑指 Offer 48. 最长不含重复字符的子字符串
又是菜菜的一天 孩子哭了
题目
菜鸡的内心想法
用哈希表能依次存储读取的字符,如果哈希表已经有这key就退出,用双重循环找出最大的,得到答案
代码 (不写注释应该看得懂吧 小声逼逼)
class Solution {
public int lengthOfLongestSubstring(String s) {
String ss="";
int max=0;
HashMap<Character,Character> map = new HashMap<Character,Character>();
for(int i=0;i<s.length();i++){
ss="";
map.clear();
for(int j=i;j<s.length();j++){
if(map.containsKey(s.charAt(j))){
break;
}else{
ss=ss+s.charAt(j);
map.put(s.charAt(j),'h');
if(max<ss.length()){
max=ss.length();
}
}
}
}
return max;
}
}
结果一看排名
直接哭晕在厕所
抱怨之后 接受现实,看官方爸爸的思路
方法一:动态规划 + 哈希表
- 哈希表统计: 遍历字符串 ss 时,使用哈希表(记为 dicdic )统计 各字符最后一次出现的索引位置 。
左边界 ii 获取方式: 遍历到 s[j]s[j] 时,可通过访问哈希表 dic[s[j]]dic[s[j]] 获取最近的相同字符的索引 ii 。 - 复杂度分析:
时间复杂度 O(N)O(N) : 其中 NN 为字符串长度,动态规划需遍历计算 dpdp 列表。
空间复杂度 O(1)O(1) : 字符的 ASCII 码范围为 00 ~ 127127 ,哈希表 dicdic 最多使用 O(128) = O(1)O(128)=O(1) 大小的额外空间。
public int lengthOfLongestSubstring(String s) {
int max=0;
int i=-1;
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int j=0;j<s.length();j++){
char temp=s.charAt(j);
if(map.containsKey(temp)){
i = Math.max(map.get(temp),i);
}
map.put(temp,j);
max=Math.max(max,j-i);
}
return max;
}
思路:
采用双指针,当对应的值存在哈希表中,更新左指针
i = Math.max(map.get(temp),i)
然后返回最大值