Leetcode 3. 반복 문자가 없는 가장 긴 부분 문자열
예 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;
};
Reference
이 문제에 관하여(Leetcode 3. 반복 문자가 없는 가장 긴 부분 문자열), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/cod3pineapple/leetcode-3-longest-substring-without-repeating-characters-3oab텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)