手撕算法-无重复字符的最长子串

描述

分析

滑动窗口,记录窗口中的所有出现的字符,然后窗口左边界固定,右边界右滑,如果,窗口中不存在新的字符,则右滑成功,否则左边界右滑,直到窗口中不存在右边界的值。

描述感觉不清晰,直接看代码吧!!

代码

版本1:

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int left = 0, right = 0;
        Set<Character> set  = new HashSet<>();

        int max = 0;

        while(right < s.length()) {
            if(!set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                right++;
            } else {
                set.remove(s.charAt(left));
                max = Math.max(max, right - left);
                left++;
            }
        }

        // 最后到终点了,也要再次判断最长长度
        max = Math.max(max, right - left);

        return max;
    }
}

版本2:(面试官推荐的版本)

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> dic = new HashMap<>();
        int i = -1, res = 0, len = s.length();
        for(int j = 0; j < len; j++) {
            if (dic.containsKey(s.charAt(j)))
                i = Math.max(i, dic.get(s.charAt(j))); // 更新左指针 i
            dic.put(s.charAt(j), j); // 哈希表记录
            res = Math.max(res, j - i); // 更新结果
        }
        return res;
    }
}

面试公司

阿里

相关推荐
liulilittle4 分钟前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师11 分钟前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
勤奋的知更鸟17 分钟前
Java 编程之模板方法模式
java·开发语言·模板方法模式
逸风尊者38 分钟前
开发易掌握的知识:GeoHash查找附近空闲车辆
java·后端
ゞ 正在缓冲99%…39 分钟前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
碎叶城李白1 小时前
若依学习笔记1-validated
java·笔记·学习·validated
上单带刀不带妹1 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
Kaltistss2 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
都叫我大帅哥2 小时前
🌊 Redis Stream深度探险:从秒杀系统到面试通关
java·redis
都叫我大帅哥2 小时前
Redis持久化全解析:从健忘症患者到记忆大师的逆袭
java·redis