Leetcode 3. 반복 문자가 없는 가장 긴 부분 문자열

문자열 s가 주어지면 문자를 반복하지 않고 가장 긴 부분 문자열의 길이를 찾습니다.

예 1:



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

예 2:



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

예 3:



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

예 4:



Input: s = ""
Output: 0

해결책



시간 복잡도 : O(n)

var lengthOfLongestSubstring = function(s) {
    let start = 0;
    let output = 0;
    let map = {}
    // In each loop currentLetter gets saved in the map
    // with its index+1 as the value
    for(let end = 0; end < s.length; end++) {
        const currentLetter = s.charAt(end);
       // If we have encountered currentLetter before,
       // we move the start pointer to the value
       // of currentLetter in the map or 
       // keep the start pointer the same depending 
       // on which value is greater
        if (map[currentLetter]!==undefined) {
          // This prevents the start pointer from decreasing
          start = Math.max(map[currentLetter], start);
        }
        output = Math.max(output, end - start + 1);
        // Add 1 to the index to prevent the currentLetter
        // from being included in the window when
        // currentLetter is encountered again
        map[currentLetter]=end+1;
    }
    return output;
};

좋은 웹페이지 즐겨찾기