【leetcode刷题笔记】Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
题解:贪心算法。
利用一个hashmap存放当前最长的无重substring所包含的元素,变量leftbound存放当前的最左边界。则当前遍历的字符s[i]有两种情况:
- s[i]所指的元素已经存在在map中了,那么就左移leftbound直到leftbound到i这一段不再包含s[i],并且在map中清除leftbound扫过的元素;
- s[i]所指的元素不在map中,保持leftbound不动,查看是否需要更新当前最长substring的长度。
代码如下:
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if(s == null || s.length() == 0) 4 return 0; 5 6 HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 7 int leftebound = 0; 8 int answer = 0; 9 10 for(int i = 0;i < s.length();i++){ 11 char current = s.charAt(i); 12 if(map.containsKey(s.charAt(i))){ 13 while(s.charAt(leftebound) != current && leftebound < i){ 14 map.remove(s.charAt(leftebound)); 15 leftebound++; 16 } 17 leftebound++; 18 } 19 else { 20 map.put(current, 0); 21 answer = Math.max(i-leftebound+1, answer); 22 } 23 } 24 25 return answer; 26 } 27 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了