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

原题链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // 思路:
        // 类似双指针加set集合并用
        // i 到 j 表示找的这个串
        // 这个串的字符都在set里,
        // 如果没有重复的,往后找并加入到 set 里面去
        // 如果遇到重复的,set的对应值去掉
        int i = 0, j = 0, res = 0;
        int n = s.length();
        Set<Character> set = new HashSet<Character>();
        while (i < n && j < n){
            // 如果不包含则加入到set里去
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j));
                j++;
            } else{
                set.remove(s.charAt(i));
                i++;
            }
            res = Math.max(res, j-i);
        }
        return res;
    }
}

  要点:双指针思维+set 的运用

原文地址:https://www.cnblogs.com/junbaba/p/14163357.html