Skip to content

003. Longest Substring Without Repeating Characters

难度: Medium

刷题内容

原题连接

  • https://leetcode.com/problems/longest-substring-without-repeating-characters/

内容描述

Given a string, find the length of the longest substring without repeating characters.

Example 1:

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

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

解题方案

思路 1 **- 时间复杂度: O(N^2)*- 空间复杂度: O(N)***

暴力解法

代码:

/**
 * @param {string} s
 * @return {number}
 */
let lengthOfLongestSubstring = function (s) {
    let result = 0;
    for (let i = 0, len = s.length; i < len; i++) {
        let set = new Set();
        set.add(s.charAt(i));
        for (let j = i + 1; j < len; j++) {
            if (set.has(s.charAt(j))) {
                break;
            }
            set.add(s.charAt(j));
        }
        result = Math.max(result,set.size);
    }
    return result;
};

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组