zoukankan      html  css  js  c++  java
  • 3. 无重复字符的最长子串

    传送门

    代码

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            Set<Character> set = new HashSet<>();
            int ans = 0,n = s.length();
            for(int r = -1,l = 0;l < n; ++l) {
                if(l != 0) {
                    set.remove(s.charAt(l - 1));
                }
                while(r + 1 < n && !set.contains(s.charAt(r + 1))) {
                    set.add(s.charAt(r + 1));
                    r ++;
                }
                ans = Math.max(ans,r - l + 1);
            }
            return ans;
        }
    }
    

    思路

    双指针 (O(n))
    用 HashSet 来做去重
    每次循环 左指针向右走一步,同时把 HashSet 中对应的元素删除
    同时,让 右边指针 一直向右走,走到不能走为止(指针越界 或者 HashSet 已经包含了相同元素)
    每次都更新一边 ans 的值即可

  • 相关阅读:
    template(2.2)
    Filter过滤链条
    The 3n + 1 problem
    Struts2.3+Spring4.0
    康托展开
    templates(2.1)
    templates(1.2)
    templates(1.1)
    我和你
    Android 的上下文菜单: Context Menu
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/14132641.html
Copyright © 2011-2022 走看看