3. Longest Substring Without Repeating Characters

解法一

思路

Brute Force 解法:For each character, find the longest non-duplicate substring starting from the character. As long as there is a duplicate character, move to next iteration. Update the maximum length in each iteration. Check duplicate by HashSet.

代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int length;
        int max = 0;
        int i = 0;
        HashSet<Integer> set;
        Loop:
        while (i < s.length()) {
            length = 0;
            set = new HashSet<>();
            int j = i;
            while (j < s.length() && !set.contains(s.charAt(j))) {
                    set.add(s.charAt(j));
                    j++;
                    length++;
                    max = Math.max(max, length);
            }
            i++;
        }
        return max;
    }
}
复杂度分析
  • 时间复杂度
    O(n^2) since there are two while loops.
  • 空间复杂度
    O(n) since we have a HashSet for detecting duplicate.

解法二

思路

Sliding windows. Set two pointers starting at the beginning of the string. Move one pointer forward as long as there is no duplicate indicating by a HashSet. Also add the character into the HashSet. If there is a character duplicates, just remove the character at i until there is no duplicate in the HashSet.

代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0; int j = 0;
        HashSet<Character> set = new HashSet<>();
        int max = 0;
        int length = 0;
        while (i < s.length() && j < s.length()) {
            if (!set.contains(s.charAt(j))) {
                set.add(s.charAt(j));
                j++;
                max = Math.max(max, ++length); // j - 1
            } else {
                set.remove(set.charAt(i++));
                length--; // 可以省略,长度更新用 j - 1
            }
        }
        return max;
    }
}
复杂度分析
  • 时间复杂度
    Worst case: O(2n): Consider the case: sqwjhjfee. The last character is the duplicate.
  • 空间复杂度
    O(n)

Optimized Sliding Window

Store the index of characters in a HashMap, so once a dulicate appears, we can immdiately skip to the position of the character first appears.

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0; int j = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0;
        int length = 0;
        while (i < s.length() && j < s.length()) {            
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            max = Math.max(max, j - i + 1);
            map.put(s.charAt(j), ++j);
        }
        return max;
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!