hot100 3.无重复字符的最长子串

思路:滑动窗口。

复杂度分析:

1.时间复杂度:O(n)。

2.空间复杂度:O(1)。

(一)方法一:整型数组

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        int res = 0;
        int left = 0;
        int[] cnt = new int[128]; //ASCII码的字符集有128个字符
        for(int right = 0;right < n;right++){
            char c = chars[right];
            cnt[c]++;
            while(cnt[c] > 1){ //窗口内有重复元素
                cnt[chars[left]]--; //移除窗口左端点字母
                left++; //缩小窗口
            }
            res = Math.max(res,right - left + 1); //更新窗口长度的最大值
        }
        return res;
    }
}

(二)方法二:布尔数组

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        int res = 0;
        int left = 0;
        boolean[] has = new boolean[128]; //ASCII码的字符集有128个字符
        for(int right = 0;right < n;right++){
            char c = chars[right];
            // 如果窗口已经包含c,那么再加入一个c会导致窗口内有重复元素
            // 所以要在加入c之前,先移出窗口内的c
            while(has[c]){ //窗口内有c
                has[chars[left]] = false;
                left++; //缩小窗口
            }
            has[c] = true; //加入c
            res = Math.max(res,right - left + 1); //更新窗口长度的最大值
        }
        return res;
    }
}
相关推荐
海绵宝宝转agent4 小时前
leetCode100算法开源笔记分享
笔记·算法
写后端的胖头鱼4 小时前
时间复杂度 & 空间复杂度
java·数据结构·算法·时间复杂度·空间复杂度
多弗朗皮卡丘4 小时前
数据结构番外:环形队列
数据结构·c
hahaha60164 小时前
黑体轨迹和色温--光源白点
人工智能·嵌入式硬件·算法·计算机视觉
海绵宝宝转agent4 小时前
基于Redis ZSet+AOP+注解实现限流注解算法
数据库·redis·算法
50万马克的面包5 小时前
顺序表和链表_精华知识点_CSDN博客
数据结构·链表
All for pursuit.5 小时前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
白杨尚青5 小时前
C++入门篇(十三):vector(上)——动态数组:构造、空间增长与迭代器失效
开发语言·c++·笔记·算法·stl
Jasmine_llq5 小时前
《P17461 [GESP202609 八级] 生成树计数》
算法·栈·tarjan 算法·边双连通分量·深度优先搜索 dfs·tarjan 保存当前路径节点·模乘法
Jasmine_llq5 小时前
《P17462 [GESP202609 八级] 末班车》
算法·dijkstra 算法·最大化版本,求最长可行值·建反向图(逆图 / 反转边)·多源 dijkstra 思想·对每个终点单独跑一遍djst·离线预处理 + 在线查询