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;
    }
}
相关推荐
iAkuya6 小时前
(leetcode)力扣100 58组合总和(回溯)
算法·leetcode·职场和发展
80530单词突击赢6 小时前
C++关联容器深度解析:set/map全攻略
java·数据结构·算法
m0_561359676 小时前
代码热更新技术
开发语言·c++·算法
_F_y6 小时前
链表:重排链表、合并 K 个升序链表、K 个一组翻转链表
数据结构·链表
xu_yule6 小时前
算法基础—组合数学
c++·算法
爱尔兰极光6 小时前
LeetCode--移除元素
算法·leetcode·职场和发展
XLYcmy6 小时前
一个用于统计文本文件行数的Python实用工具脚本
开发语言·数据结构·windows·python·开发工具·数据处理·源代码
方便面不加香菜6 小时前
数据结构--链式结构二叉树
c语言·数据结构
senijusene6 小时前
数据结构:单向链表(2)以及双向链表
数据结构·链表
Tansmjs6 小时前
C++中的工厂模式变体
开发语言·c++·算法