3. Longest Substring Without Repeating Characters

题目描述

给定一个字符串,找到最长子字符串的长度,其中不存在重复字符。

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

解题思路1:暴力法

参考代码1

public int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<>();
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            int len = 0;
            int j = i;
            while (j < s.length() && !set.contains(s.charAt(j))) {
                set.add(s.charAt(j));
                len++;
                j++;
            }
            max = Math.max(max, len);
            set.clear();
        }
        return max;
    }

解题思路2

在暴力法中我们看到,每次检查完一个子序列 [i, j] 后,我们清空了 set ,使得从 i + 1 开始查找,这样的话 [i + 1, j] 序列不就重复了吗?
其实可以不使用 clean() 方法,而是从 set 中去掉 第 i 个元素,这样的话序列就可以保留下来。

【LeetCode】 3. Longest Substring Without Repeating Characters

图片来源:https://github.com/MisterBooo/LeetCodeAnimation

参考代码2

public int lengthOfLongestSubstring(String s) {
         Set<Character> set = new HashSet<>();
        int max = 0;
        int i = 0, j = 0;
        while (i < s.length() && j < s.length()) {
            if (!set.contains(s.charAt(j))) {
                set.add(s.charAt(j));
                j++;
            } else {
                set.remove(s.charAt(i));
                i++;
            }
            max = Math.max(max, j - i);
        }
        return max;
    }

相关文章:

  • 2022-01-10
  • 2021-05-17
  • 2022-02-05
  • 2021-12-25
  • 2021-10-31
  • 2021-07-25
猜你喜欢
  • 2021-09-05
  • 2021-10-03
  • 2021-06-04
  • 2021-09-12
  • 2021-12-23
  • 2021-09-14
  • 2021-11-20
相关资源
相似解决方案