LeetCode3. 无重复字符的最长子串

一、题目描述

二、解法

思路:滑动窗口

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        /*int l = 0, r = 0;
        int res = 0;
        char[] chars = s.toCharArray();
        HashSet set = new HashSet();
        while (l < chars.length && r < chars.length) {
            if (set.contains(chars[r])) {
                set.remove(chars[l]);
                l ++;
            }else {
                set.add(chars[r]);
                r ++;
            }
            res = Math.max(res, set.size());

        }
        return res;*/
        int l = 0, r = 0;
        int res = 0;
        int[] freq = new int[256];
        char[] chars = s.toCharArray();
        while (l < chars.length && r < chars.length) {
            if (freq[chars[r]] == 0) {
                freq[chars[r]] ++;
                res = Math.max(res, r - l + 1);
                r ++;
            }else {
                freq[chars[l]] --;
                l ++;
            }
        }
        return res;
    }
}

 

posted @ 2020-12-07 18:13  不学无墅_NKer  阅读(56)  评论(0编辑  收藏  举报