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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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